Self-determination function and parameters?

I saw the following way of writing self-starting functions:

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

Where App is a global object.

I wonder why we need to pass the App as a parameter to a function? Why not just use this:

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

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

Are there any other differences?

+4
source share
4 answers

This means that the contents of the function β€” in relation to the identifier app β€” are agnostic for the global (or parent) scope.

One of the scenarios in which this is done is, for example, jQuery, when you do not want to assume that the jQuery object is called $ (for example, if there is no conflict mode), but you want to call it a name. Passing it through an anonymous function like this one (i.e. (function($) {})(jQuery) ) allows you to generate a local scope alias that does not interfere with the external value of the name $ in the parent / global scope.

+9
source

Other answers explain the benefits of having a copy with local coverage. There are several more advantages:

  • As a micro-optimization, it reduces the visibility of the search area (less expensive searching for local var than global).
  • This can help in the minimization process, since all your parameters are reduced to one letter with the name vars.
  • This gives you a pseudo-dependency management method ... in your example, you know that your code is App dependent.
+2
source

For example, many libraries use the "$" symbol as a shortcut for their main function (for example, jQuery). This is convenient, but can cause a conflict when using multiple libraries. So you can pass JQuery as follows:

 (function($) { // Code var nav = $('#nav'); // More code })(JQuery); 

Thus, you can still use a convenient shortcut, but you can also avoid collisions (provided that you also configure the libraries not to use the "$" shortcut).

+1
source

You can also use it to override global variables locally to make sure that they contain pending:

 (function($, undefined) { ... })(jQuery); 

Where undefined now expected to be undefined. Also see: What is the purpose of transmitting undefined?

Most other uses are well covered in other answers.

+1
source

All Articles