Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self-invoking function and params?

I've seen the next way of writing self-invoking functions:

(function (app) {
    app.foo = {
        bar: function(){}
    };
}(App));

Where App is a global object.

I wonder, why do we need to pass App as a param into a function? Why don't just use this:

(function () {
    App.foo = {
        bar: function(){}
    };
}());

I see only one advantage of using the first way. If we for some reason rename the App object, then we can easily rename the param in brackets and our code will work as it works. But in case of the second way we will probably need to rename App in all places where we use it.

Are there other differences?

like image 819
serg66 Avatar asked Dec 11 '22 18:12

serg66


1 Answers

It means that the contents of the function – with regards to the app identifier – are agnostic to the global (or parent) scope.

One of the scenarios in which this is done is, for example, with jQuery, when you don't want to assume that the jQuery object is called $ (e.g. if no-conflict mode is on), but you do want to call it by that name. Passing it through an anonymous function like this (i.e. (function($) {})(jQuery)) allows you to generate a locally-scoped alias that doesn't interfere with the external meaning of the name $ in the parent/global scope.

like image 77
Will Vousden Avatar answered Dec 14 '22 08:12

Will Vousden