gpt4 book ai didi

javascript - 如何保存内部作用域变量以供外部作用域使用?

转载 作者:行者123 更新时间:2023-12-01 00:53:59 25 4
gpt4 key购买 nike

如何获取变量 cool 以便可以在 gotSpeech() 函数之外使用它?我想将它用于函数 guessedCorrect(),当我单击按钮时该函数也会运行。那可能吗?

let speechRec = new p5.SpeechRec('en-US', gotSpeech);

function gotSpeech() {
if (speechRec.resultValue) {
cool = speechRec.resultString;
if (cool == "0") {
zero.style.color = "#dc3545";
}
if (cool == "5") {
five.style.color = "#dc3545";
}
if (cool == "10") {
ten.style.color = "#dc3545";
}
if (cool == "15") {
fifteen.style.color = "#dc3545";
}
if (cool == "20") {
twenty.style.color = "#dc3545";
}
}
}

button.addEventListener("click", function(event) {
resetround();
speechRec.start();
setTimeout("getComputerChoice()", 3000);
setTimeout("identifyHands()", 3000);
clearInterval(myInterval);
myInterval = setInterval(function() {
time--;
if (time == -1) {
button.innerHTML = "Again";
clearInterval(myInterval);
time = 4;
} else {
button.innerHTML = "Start";
numbers.innerHTML = time;
}
}, 1000);
setTimeout("guessedCorrect()", 5000);
})

当输出超出范围时,返回undefined

最佳答案

有很多方法可以解决这个问题。最明显的是修改对 guessedCorrect() 的调用以显式传递它:

setTimeout(() => { guessedCorrect(cool); }, 5000);

当然,这意味着您需要修改 guessedCorrect() 的定义以适应传入的参数,即:

function guessedCorrect(cool) { //...

这样做的好处是不通过字符串名称引用函数。正如@Shahzad 所说,这会导致您的代码在缩小时中断,因为缩小不会更改字符串。更好的是使用函数引用,所以:

setTimeout(guessedCorrect, 5000);

此外,通过使用 switch() block 甚至对象作为值到颜色映射,可以大大减少重复的 if/else if 博客。

[编辑]

回应您稍后的评论:

this 是当前闭包正在执行的上下文。默认上下文(即直到发生更改之前)是 window。通常上下文是自动设置的,例如在事件回调中,this 指向触发元素。但在你的例子中,我们可以(尽管这是一种相当奇怪的方法)设计 this 指向 cool 的值,所以:

setTimeout(guessedCorrect.bind(cool), 5000);

之后,在 guessedCorrect() 中调用 this 将显示调用该函数时存在的 cool 的值。

关于javascript - 如何保存内部作用域变量以供外部作用域使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56743193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com