【问题标题】:JavaScript - Nested function dropping .length of arrayJavaScript - 嵌套函数删除数组的 .length
【发布时间】: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


【解决方案1】:

正如 cmets 指出的那样,anyKey() 嵌套在 testFunc() 中,它只是从 testFunc() 中调用。这不足以共享相同的范围。这是一个嵌套在另一个函数中的示例,显示它们共享一个变量keyCount,该变量跟踪一个键被按下的次数:

function testFunc() {
  let keyCount = {}
  let input = document.getElementById('myInput')
  input.addEventListener("keydown", addCount);
  
  // addCount is nested here
  function addCount(ev) {
    let key = ev.key
    // this functin has access to keyCount because it's nested
    // within testFunc
    keyCount[key] = (keyCount[key] || 0) + 1
    console.log("counts: ", keyCount)
  }
}
testFunc()
&lt;input id='myInput' type="text" /&gt;

嵌套两个函数可能不方便。另一种选择是在函数之外简单地定义hotkey,它将在两者的范围内,或者重新设计逻辑,以便只有一个函数需要访问它。例如,您的事件处理程序不需要执行太多逻辑——它只需确定按下了哪个键并将其传递给管理状态的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 2020-12-07
    • 2019-10-09
    • 1970-01-01
    • 2019-08-31
    相关资源
    最近更新 更多