简体   繁体   English

闭包中的可变范围

[英]Variable Scope in Closure

In the following code (from Secrets of the JavaScript Ninja ), I don't understand why inner | tooLate 在下面的代码中(来自JavaScript Ninja的秘密 ),我不明白为什么inner | tooLate inner | tooLate prints out ronin . inner | tooLate打印ronin I would've expected undefined . 我希望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");

My confusion is how tooLate is accessible within innerFunction . 我的困惑是如何在tooLate中访问innerFunction Isn't innerFunction 's scope limited to outerFunction ? innerFunction的范围不限于outerFunction吗?

http://jsfiddle.net/6HuaS/ http://jsfiddle.net/6HuaS/

innerFunction is under outerFunction which is under window , therefore innerFunction can access all properties and methods of window . innerFunction位于window下的outerFunction下,因此innerFunction可以访问window所有属性和方法。

In your example, tooLate is declared under the window scope (global). 在您的示例中,在window范围(全局)下声明了tooLate Since you haven't declare a new tooLate in outerFunction nor innerFunction , it will trace back all the way to window to find a declared tooLate . 由于您尚未在outerFunctioninnerFunction声明新的tooLate ,因此它将追溯到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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM