[英]JS: When making a closure, how does the inner function access the outer function argument if I'm not storing as a variable?
[英]Why is this not a closure that allows an inner function to access an outer function variable?
如何通過閉包啟用對funcB變量'e'的訪問?
<!DOCTYPE HTML>
<html>
<head>
<script>
Test = function () {};
Test.prototype.funcA = function (k) {
var that = this;
return function(e) {
window.console.log('k: ' + k); // 'abc'
window.console.log('e: ' + e); // 'def'
that.funcB(k);
};
};
Test.prototype.funcB = function (p) {
window.console.log('p: ' + p); // 'abc'
window.console.log('e: ' + e); // undefined (why?)
}
obj = new Test();
(obj.funcA('abc'))('def');
</script>
</head>
<body>
</body>
</html>
我對閉包感到困惑。
由於變量e存在於funcA(打印為'def')中,由於funcB由funcA執行,為什么funcB無法訪問它? 如何授予funcB訪問變量e?
我希望可以通過閉包訪問變量e。 我不想將其存儲在實例化的對象上(我知道我可以做到)。
您必須將“ e”的值作為參數傳遞給另一個函數。 JavaScript中的作用域是由函數的詞法關系而不是動態關系確定的。 函數中的代碼可以看到“向外”,並且從funcB()
移出不會遇到定義了“ e”的范圍。 funcB()
中唯一可見的符號是它自己的局部符號(在這種情況下為p
)和全局符號。
現在,您可以顯式地將對象“ e”的副本存儲為屬性:
return function(e) {
window.console.log('k: ' + k); // 'abc'
window.console.log('e: ' + e); // 'def'
that.e = e;
return that.funcB(k);
};
Test.prototype.funcB = function (p) {
window.console.log('p: ' + p); // 'abc'
window.console.log('e: ' + this.e);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.