Accessing variables trapped by closure

前端 未结 6 608
佛祖请我去吃肉
佛祖请我去吃肉 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:50

    Answers above are correct, but they also imply that you'll have to modify the function to see those closed variables.

    Redefining the function with the getter methods will do the task. You can do it dynamically. See the example below

    function alertMe() {
        var message = "Hello world"; 
        console.log(message);
    }
    
    //adding the getter for 'message'
    var newFun = newFun.substring(0, newFun.lastIndexOf("}")) + ";" + "this.getMessage = function () {return message;};" + "}";
    
    //redefining alertMe
    eval(newFun);
    
    var b = new alertMe();
    

    now you can access message by calling b.getMesage()

    Of course you'll have to deal with multiple calls to alertMe, but its just a simple piece of code proving that you can do it.

提交回复
热议问题