【发布时间】:2018-10-09 10:41:45
【问题描述】:
我正在尝试编写一个可以记录按键并将按键存储到名为“热键”的变量中的应用程序。这个想法是创建一个按键数组来定义一个同时按键输入和触发动作的热键。
问题是我一直遇到函数范围问题。根据我对函数范围的理解,嵌套函数(在本例中为 anyKey)应该可以访问其父范围的所有变量(在本例中为 testFunc())。
我觉得我在这里遗漏了一些重要的东西,但我不确定它是什么。我知道它与保留变量的嵌套函数有关,但它似乎应该如何工作。有任何想法吗?我需要在这里自学哪些主要概念?
提前致谢。
function testFunc() {
var hotkey = [];
console.log("hotkey length is:"+hotkey.length) //Yields "hotkey length is:0"
hotkey[0] = "dummy";
input.addEventListener("keydown", anyKey);
}
function anyKey(ev, txt, hotkey){ //If I don't enter hotkey as a paremeter, I'm notified "hotkey is not defined". If I _do_ enter it, I get "nested hotkey length is: undefined
console.log("nested hotkey length is:"+hotkey);
let target = ev.currentTarget;
let tag = target.tagName;
let char = ev.char || ev.charCode || ev.which;
log(char, tag);
let s = String.fromCharCode(char);
log(s);
/***
The following code, consequentially, doesn't work because hotkey.length isn't defined
***/
for(i = 0; i <= hotkey.length + 1; i++){
if (hotkey[i] === undefined || hotkey[i] === "dummy"){
hotkey[i] = char;
}
}
【问题讨论】:
-
您是否意识到函数
anyKey超出了testFunc的范围?因此,任何局部变量都无法从函数anyKey访问 -
"嵌套函数(在本例中为 anyKey)应有权访问其父作用域的所有变量(在本例中为 testFunc())"。没错,但这里
anyKey不是testFunc()的嵌套函数
标签: javascript scope nested-function