You do not know the JS series (10) - Perform a function expression immediately

Immediate execution function expression (IIFE, Immediately Invoked Function Expression)
(function foo(){
  var a = 3;
  console.log(3);
})()
Such (funciton foo () {...}) (). The first () function will become expression and the second () to perform this function.

 

Compared with the traditional IIFE many people prefer another refinement, ((funciton foo () {...}) ()), a first form of expression is a function contained in the (), and then with the other in the back a () brackets to call. The second form is used to call () is moved into the bracket for packaging () parentheses. The choice of which depends on personal preference.

 

Another is the use of advanced IIFE them as a function call and pass parameters into account
var a = 2;
(function IIFE(global){
  var a = 3;
  console.log(a); // 3
  console.log(global.a) // 2
})(window);
console.log(a); // 2

References on code style to become a global object variable is no global than a word clearer. Can pass anything you need from the outer scope, which is to improve code style is very helpful

 

IIFE Another use is to run an inverted code sequence, although this pattern somewhat lengthy, but some people think it's easier to understand
var a = 2;
(function IIFE(def){
  def(window)
})(function def(global){
  var a = 3;
  console.log(a); // 3
  console.log(global.a); //2
})

 

Guess you like

Origin www.cnblogs.com/wzndkj/p/12340443.html