javascript - 嵌套函数丢失变量引用

标签 javascript scope

在下面的代码中:

function outer() {
  var x = 'foo';

  function inner() {
    var y = x;     // y == 'foo'
    var x = 'bar'; // x == 'bar', y == undefined
  }
}

为什么变量yinner() 内变得未定义?它不应该指xouter()

如果行 var x = 'bar';然后 y 被删除确实具有值“foo”。

最佳答案

inner 函数被解释为就像这样编写的:

  function inner() {
    var y;
    var x;
    y = x;     // y == undefined
    x = 'bar'; // x == 'bar'
  }

声明被提升,但初始化是从上到下处理的。因此,在整个 inner 函数中,符号 xy 都引用了该函数中本地声明的变量。功能;特别是 x 是本地 x,而不是封闭上下文中的 x。因此,当计算 y 的初始化表达式时,x 是尚未初始化的本地 x;它的初始值设定项表达式位于 y 的初始值设定项之后

关于javascript - 嵌套函数丢失变量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36894942/

相关文章:

javascript - AngularJS 表单未绑定(bind)到 $http 请求

javascript - 选中复选框时添加类并更改内部 HTML

javascript - Google 脚本运行时优化

javascript - items = [].concat(items) 它有什么作用?

javascript - 回调函数作用域在 "new"on JS object literal

javascript - 从 JS 中的 'success' block 返回值(Azure 移动服务)

c++ - 具有结构的嵌套类的范围

javascript - 通过主干使用 RESTful api

javascript - 如何将 ng-model/$scope 与 Angular Factory 和 Controller 一起使用

powershell - 在Powershell中使用子脚本修改父脚本中的变量