简体   繁体   中英

What way (if any) can I get the reference to anonymous function's closure in javascript?

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?

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).

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'

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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM