簡體   English   中英

閉包中的可變范圍

[英]Variable Scope in Closure

在下面的代碼中(來自JavaScript Ninja的秘密 ),我不明白為什么inner | tooLate 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");

我的困惑是如何在tooLate中訪問innerFunction innerFunction的范圍不限於outerFunction嗎?

http://jsfiddle.net/6HuaS/

innerFunction位於window下的outerFunction下,因此innerFunction可以訪問window所有屬性和方法。

在您的示例中,在window范圍(全局)下聲明了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