简体   繁体   English

为什么这不是允许内部函数访问外部函数变量的闭包?

[英]Why is this not a closure that allows an inner function to access an outer function variable?

How do I enable access to variable 'e' in funcB via a closure? 如何通过闭包启用对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>

I'm confused about closures. 我对闭包感到困惑。

Since variable e exists in funcA (printed 'def'), why can funcB not access it since funcB is executed by funcA? 由于变量e存在于funcA(打印为'def')中,由于funcB由funcA执行,为什么funcB无法访问它? How do I give funcB access to variable e? 如何授予funcB访问变量e?

I want variable e to be accessible via a closure. 我希望可以通过闭包访问变量e。 I don't want to store it on the instantiated object (which I know I could do). 我不想将其存储在实例化的对象上(我知道我可以做到)。

You'll have to pass the value of "e" to the other function as a parameter. 您必须将“ e”的值作为参数传递给另一个函数。 Scoping in JavaScript is determined by the lexical relationship of functions, not the dynamic relationship. JavaScript中的作用域是由函数的词法关系而不是动态关系确定的。 Code in a function can see "outwards", and moving out from funcB() does not encounter a scope with "e" defined. 函数中的代码可以看到“向外”,并且从funcB()移出不会遇到定义了“ e”的范围。 The only symbols visible to code in funcB() are its own local symbols ( p in this case) and global symbols. funcB()中唯一可见的符号是它自己的局部符号(在这种情况下为p )和全局符号。

Now, you could explicitly stash a copy of "e" on the object itself as a property: 现在,您可以显式地将对象“ 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.

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