Accessing variables trapped by closure

前端 未结 6 606
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 06:38

I was wondering if there is any way to access variables trapped by closure in a function from outside the function; e.g. if I have:


A = function(b) {
    va         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 06:42

    A simple eval inside the closure scope can still access all the variables:

    function Auth(username)
    {
      var password = "trustno1";
      this.getUsername = function() { return username }
      this.eval = function(name) { return eval(name) }
    }
    
    auth = new Auth("Mulder")
    auth.eval("username") // will print "Mulder"
    auth.eval("password") // will print "trustno1"
    

    But you cannot directly overwrite a method, which is accessing closure scope (like getUsername()), you need a simple eval-trick also:

    auth.eval("this.getUsername = " + function() {
      return "Hacked " + username;
    }.toSource());
    auth.getUsername(); // will print "Hacked Mulder"
    

提交回复
热议问题