简体   繁体   中英

Javascript: How can two self executing function access each other

I get what a Javascript self executing anonymous function is:

(function(){
    console.log('Hello World!');
})();

and I get you can pass in parameters:

(function(window){
   window.location(...);
})(window);

But if I have two self executing anonymous functions, can each one access the other? Specifically, How can the first function call a method from the second, passing it a variable?

(function(){
    function foo () {
        return 'foo';
    }

    // How can I call "bar('my name is')"
})();

(function(){
    function bar (str) {
        return str + ' bar' ;
    }
})();

Thanks for listening.

They can't and that's kinda the point. By wrapping code like this, its inaccessible from the outside.

If you don't care about such accessibility protections the other things you could do is:

function foo() { bar() } // call bar
foo(); // execute immediately
function bar() { // do stuff }
bar(); // also execute immediately

If you declare or initialise a function within a particular execution context, you can only access it from the same execution context or another that has the first one on its scope chain. It doesn't matter whether the outer context is "anonymous" or not. Eg in the following:

(function(){
    function foo () {return 'foo';}
})();

foo is just as inacessible as if you'd done:

(function(){
    var foo = function () {return 'foo';};
})();

or

function bar(){
    function foo () {return 'foo';}
}
bar();

In this case, a closure may be used:

var foo = (function(){
    var /* variables to hold in a closure */

    function foo () {return 'foo';}

    // Return a reference to foo
    // foo has a closure to this execution context
    return foo;
})();

(function() {
  // call foo here and pass parameters
  foo(...);
}());

You could also have the IIFE as:

var foo = (function(){
    var /* variables to hold in a closure */

    // Return a reference to a function
    // that has a closure to this execution context
    return function () {return 'foo';}

}());

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