Accessing variables trapped by closure

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

    If you only need access to certain variables and you can change the core code there's one easy answer that won't slowdown your code or reasons you made it a closure in any significant way. You just make a reference in the global scope to it basically.

    (function($){
        let myClosedOffObj = {
            "you can't get me":"haha getting me would be useful but you can't cuz someone designed this wrong"
        };
        window.myClosedOffObj = myClosedOffObj;
    })(jQuery);
    myClosedOffObj["you can't get me"] = "Got you now sucker";
    

    Proof of concept: https://jsfiddle.net/05dxjugo/

    This will work with functions or "methods" too.

提交回复
热议问题