iife:immediately-invoked function expression
(1) standard notation
1 (function(window, document, undefined) {2 //3 }) (window, document);
For example:
1 // JQuery 2 (function($) {}) (jQuery); 3 // MUI 4 (function($) {}) (MUI);
(2) Scope scope
JavaScript has a function scope, so function first creates a private scope and creates an execution context when it executes.
1 varLogmyname =function(name) {2 Console.log (name);3 };4Logmyname (' John Doe ');5 6 varLogmyname = (function(name) {7 Console.log (name);8}) (' Harry ');9 Ten varA =!function() { One return true; A }(); -Console.log (a);//Print output False - the varB = (function() { - return true; - })(); -Console.log (b);//Print Output True + - //force JavaScript to recognize code (rarely used in this way) +!function() { A // ... at }(); - -+function() { - // ... - }(); - in-function() { - // ... to }(); + -~function() { the // ... *}();
1(function($, window, document, undefined) {2 //use $ to point to jQuery, such as:3 //$ (document). addclass (' test '); 4 }) (JQuery, window, document);5 6(function(A, B, C, d) {7 //the code will be compressed to:8 //A (c). addclass (' test '); 9}) (JQuery, window, document);
Transferred from: http://rensanning.iteye.com/blog/2080429
JavaScript Iife (Instant execution method)