javascript - 闭包中的变量作用域

标签 javascript

在下面的代码中(来自Secrets of the JavaScript Ninja),我不明白为什么inner | tooLate 打印出 ronin。我希望 undefined

var outerValue = "ninja";
var later;

function outerFunction() {
    var innerValue = "samurai";

    function innerFunction(paramValue) {
        console.log("outerValue:",outerValue);
        console.log("innerValue:",innerValue);
        console.log("paramValue:",paramValue);
        console.log("inner | tooLate", tooLate);
    }
    later = innerFunction;
}

console.log("outer | tooLate", tooLate);

var tooLate = "ronin";

outerFunction();
later("warrior");

我的困惑是如何在 innerFunction 中访问 tooLateinnerFunction 的范围不是限制在outerFunction 吗?

http://jsfiddle.net/6HuaS/

最佳答案

innerFunctionouterFunction 下在 window 下,因此 innerFunction可以访问 window 的所有属性和方法.

在您的示例中,tooLatewindow 下声明范围(全局)。由于您尚未声明新的 tooLateouterFunction也不innerFunction ,它会一直追溯到window找到声明的 tooLate .

var b, val = 0;
function a(){
    b = function (){
        console.log(val);
    }
}
a();
val = 2;
b();  //2
Scope:

window
├─ a: function
│ └─ b: function      b can access variables in a, b, and all the way to window
└─ val: number         if the variable name hasn't been overridden

关于javascript - 闭包中的变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20865479/

相关文章:

javascript - Internet Explorer总是在unload之前触发窗口

javascript - 将整个 DOM 复制到新窗口

javascript - 无法在 threejs 中加载 json 文件

JavaScript - 重复字符的动态正则表达式

javascript - 两个代码之间的差异

javascript - react - Uncaught Error : Target container is not a DOM element

javascript - react : How to check the type of a child in the parent's render function?

Javascript 全局变量无法正常工作?

javascript - 如何避免发布特定输入?

javascript - es6 传播运算符如何处理对象到 Prop 的转换?