[英]How do I save inner scope variable to use with outside scope?
如何獲得變量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()
塊甚至一個對象作為顏色到顏色的映射,可以大大減少您重復的if/else if
博客。
[編輯]
回應您以后的評論:
this
是當前關閉正在執行的上下文。 默認上下文(即直到某些更改)是window
。 上下文通常是自動設置的,例如在事件回調中, this
指向觸發元素。 但是,在你的情況下,我們可能會(雖然這將是一個相當奇怪的方法)圖謀this
指向的值cool
,所以:
setTimeout(guessedCorrect.bind(cool), 5000);
之后,在guessedCorrect()
調用this
guessedCorrect()
將調出調用函數時存在的cool
值。
好吧,您實際上需要的是值而不是變量。 以及您已經可以使用speechRec.resultString
點表示法訪問的值。
您可以嘗試這樣的事情:
// An modification that the post from above offers you, which is pretty good for this case. value-to-colours
const colors = {
0: '#dc3545',
5: '#dc3545',
10: '#dc3545',
15: '#dc3545',
20: '#dc3545',
};
function gotSpeech() {
if (speechRec.resultValue) {
zero.style.color = colors[speechRec.resultString];
}
}
button.addEventListener("click", function(event) {
resetround();
speechRec.start();
// Why are you passing the functions as string?
// Better do this
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.bind(null, speechRec.resultString), 5000);
})
如果您的guessedCorrect
函數是從另一個文件導出的,那么我將使用bind
函數使用給定的參數創建一個新函數。 否則,如果函數在同一個文件中,則只需傳遞如下函數:
setTimeout(guessedCorrect, 5000);
在函數中,只需使用全局變量speechRec.resultString
。
注意:嘗試使用嚴格比較(
===
)而不是抽象(==
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.