How do I enable access to variable 'e' in funcB via a closure?
<!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? How do I give funcB access to variable e?
I want variable e to be accessible via a closure. 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. Scoping in JavaScript is determined by the lexical relationship of functions, not the dynamic relationship. Code in a function can see "outwards", and moving out from funcB()
does not encounter a scope with "e" defined. The only symbols visible to code in funcB()
are its own local symbols ( p
in this case) and global symbols.
Now, you could explicitly stash a copy of "e" on the object itself as a property:
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.