Is it possible to gain access to the closure of a

2019-01-03 17:50发布

A function in javascript forms a closure by keeping a (hidden) link to its enclosing scope.

Is it possible to access it programmatically when we have the function (as a variable value) ?

The real goal is theoretical but a demonstration could be to list the properties of the closure.

var x = (function(){
   var y = 5;
   return function() {
       alert(y);
   };
})();

//access y here with x somehow

3条回答
Evening l夕情丶
2楼-- · 2019-01-03 18:05

That's (one of) the purpose(s) of a closure - to keep information private. Since the function already has been executed its scope variables are no longer available from outside (and have never been) - only the functions executed in it's scope (still) have access.

However you could give access via getters/setters.

You might want to take a look into Stuart Langridge's talk about closures. Very recommendable are also Douglas Crockfords Explanations. You can do lots of fancy stuff with closures;)

Edit: You have several options to examine the closure: Watch the object in the webdeveloper console or (as I do it often) return a debug-function which dumps out all the private variables to the console.

查看更多
不美不萌又怎样
3楼-- · 2019-01-03 18:07

No, not unless you expose it:

var x = function(){
        var y = 5;

        return {             
           getY: function(){
              return y;
          },
          setY: function(newY){
             y = newY;
          }    
       }
   }


    x.setY(4);
查看更多
孤傲高冷的网名
4楼-- · 2019-01-03 18:17

You can edit the alert function:

var x = (function(){
   var y = 5;
   return function() {
       alert(y);
   };
})();

var oldAlert = alert;

alert = function (x) {
    oldAlert(x);
    window.y = x;
}

x();

console.log(y); // 5

Or if you own the code, you can use standart getters and setters.

查看更多
登录 后发表回答