2 回答

TA貢獻1815條經驗 獲得超6個贊
有很多方法可以解決這個問題。最明顯的是修改您的調用guessedCorrect()
以顯式傳遞它:
setTimeout(() => { guessedCorrect(cool); }, 5000);
當然,這意味著您需要修改 的定義guessedCorrect()
以適應傳入的參數,即:
function guessedCorrect(cool) { //...
這具有不通過字符串名稱引用函數的額外優勢。正如@Shahzad 所說,這會導致您的代碼在縮小時中斷,因為縮小不會改變字符串。更好的是使用函數引用,所以:
setTimeout(guessedCorrect, 5000);
此外,if/else if
通過使用switch()
塊甚至對象作為顏色值映射可以大大減少您重復的博客。
[編輯]
回應你后來的評論:
this
是正在執行當前閉包的上下文。默認上下文,即直到有什么改變它,是window
。通常上下文是自動設置的,例如在this
指向觸發元素的事件回調中。但是在您的情況下,我們可以(盡管這將是一種相當奇怪的方法)設法this
指向 的值cool
,因此:
setTimeout(guessedCorrect.bind(cool), 5000);
之后,調用this
insideguessedCorrect()
將調出調用cool
函數時存在的值。

TA貢獻1936條經驗 獲得超7個贊
好吧,您實際上需要的是值而不是變量;以及您已經可以使用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。
注意:盡量使用嚴格比較 ( ===) 而不是抽象 ( ==)。
添加回答
舉報