javascript self executing function

  • 2021-07-18 07:09:46
  • OfStack


function (window, $, undefined) {
 play=function(){
  $("#demo").val("This is a demo.");
 }
 window.wbLogin = play;
})(window, jQuery);

Why should code like the above pass in window and jQuery objects?

Why pass in jQuery?

By defining an anonymous function, a "private" namespace is created, and the variables and methods of this namespace will not destroy the global namespace. This is very useful and must be supported by an JS framework. jQuery is used in thousands of JavaScript programs, and it is necessary to ensure that the variables created by jQuery cannot conflict with the variables used by the imported programs.

Why pass in window?

By passing in window variable, window changes from global variable to local variable. When accessing window in jQuery code block, there is no need to retreat the scope chain to the top-level scope, so that window can be accessed faster; This is not the point, but more importantly, passing in window as a parameter can be optimized when compressing code, see jquery-1. 6.1. min. js:

(function(a,b){})(window); // window 被优化为 a

Why pass in undefined?

In the scope of self-calling anonymous functions, ensure that undefined is really undefined. Because undefined can be overridden and given a new value.

1 sentence, make the global variable become the local variable inside the self-executing function in the form of parameter.

As for why to do this, improve the efficiency of the program. Why can we improve the efficiency? We have to start with the mechanism of javascript. The so-called scope chain scope chain, if there is no attribute (local variable) in the current scope, looks for it in the upper level scope, and 1 reaches the top level, that is, window. That is to say, the global variable and the subordinate scope are both one attribute of window, and so on.

In addition, writing the parameter as $after jQuery is passed in can ensure that $is jquery in this function instead of other libraries using $symbol.

undefined in the same way, since no third parameter is passed in, it is naturally undefined. Because undefined in javascript is a variable and can be changed, it can ensure the accuracy of undefined judgment. Sometimes typeof xxx === 'undefined' is used for this reason.


Related articles: