What way (if any) can I get the reference to anony

2019-09-02 12:55发布

问题:

Let us consider the workable code:

var storage = {};

(function() {
    function internalMethod1() { ...; return; }
    function internalMethod2() { ...; return; }
    storage.storedMethod = internalMethod1;
})();

storage.storedMethod();

Is there any way to call internalMethod2, if it is not called in internalMethod1? In other words, can I access an anonymous closure from outside, if I have access only to one of its functions?

回答1:

can I access an anonymous closure from outside?

No. Scopes are private in JS, and there's absolutely no way to access them from the outside (unless you use the engine's implementation-specific debugging API…).

Variables (including functions) are only available in the same scope and its children. If you want to access their values outside of the scope, you're at the mercy of the function to expose them in some way (return, assign to global storage variable etc).



回答2:

No, you cannot access a private, unreferenced scope after it has been executed. You would need to create another closure to create a reference to whatever private method you wanted to expose.

var storage = {};

(function() {
    function internalMethod1() { 
        return {
            internalPublic1: internalMethod2
        };
    }

    function internalMethod2() {  
        console.log('hi');
    }

    storage.storedMethod = internalMethod1;
})();

var a = storage.storedMethod();
a.internalPublic1(); //'hi'


回答3:

Try defining IIFE as variable , return reference to internalMethod2 from IIFE

var storage = {};

var method2 = (function() {
    function internalMethod1() { console.log(1) };
    function internalMethod2() { console.log(2) };
    storage.storedMethod = internalMethod1;
    return internalMethod2
})();

storage.storedMethod();

method2();