简体   繁体   中英

Can I change a function referenced in a Javascript closure in an anonymous scope

Given this example:

var x = function() { return(0); };
var y = function() { return(x()); };

Calling y() in the console will return 0. Changing x() in this scope will change the value returned by y(). This is possible because I have direct access to the scope of y(). However, if y() was defined in an anonymous scope, but I have access to it, but do not have direct access to x(), can I change x() to be something like:

var x = function() { return(1); };

So that calling y() will reflect this change to x()?

In other words, given access only to y(), can I grab it's scope and change x() so that calling y() will reflect that change?

No, that's not possible. In the example below, there's no way to change the x to which y refers to from outside the closure. A closure will close over it's own scope as well as it's parent scopes.

var y = (function () {
    return function y() { return x(); };
    function x() { return 0; }
})();

//There's no way to modify x from here

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.

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