简体   繁体   中英

Why assign a variable to an anonymous function and redefine it again in that function?

I've been trying to improve my JavaScript skills and I already know the advantage of having a script wrapped inside an anonymous function is to make it self invoked and keep the variables and inner functions private.

But what's the point of having an anonyous function assigned to a variable and then again inside that function the same variable as an empty object? Is it to clear it?

And at the end the end of the function what is the purpose of return ?

var app = (function () {
    'use strict';

    var app = {};

    //more code

    return app;
})();

As you have mentioned you use this syntax to create a closure, so you can keep variables private and exposed and Interface as a API, so why you return and empty or filled object into the closure?, this works as a public method to be used , this is helpful to avoid context collision between your API and external API (libs).

var api = (function(jqueryRef){
                   var $ = {
                      addClass: jqueryRef.addClass,
                      yourOwnAddClassFn: ...
                    };
                    return $;
                 })($);

As you can see you can passing an jquery reference as a parameter, and can use it into your closure, then you can use the $ common jquery namespace into your API without collision.

What you're looking for is called scope . Have a look at this example taken from scotch.io :

// global scope (scopeA)
var Module = (function() {
    // scope is now everything in this function (scopeB)
    function privateMethod() {
        console.log('privateMethod called!')
    }

    return {
        publicMethod: function() {
            // this function has access to scopeB 
            console.log('publicMethod called!');
            privateMethod();
        }
    };
})();


Module.publicMethod(); // gives publicMethod called!
Module.privateMethod(); // Uncaught ReferenceError: privateMethod is not defined

The explanation of this from scotch is actually pretty good so I'll just quote it:

The return statement of the Module contains our public functions. The private functions are just those that are not returned. Not returning functions makes them inaccessible outside of the Module namespace. But our public functions can access our private functions which make them handy for helper functions, AJAX calls, and other things.

I hope this clears things for you.

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