Execute function immediately, and its two ways of writing

Execute function immediately

1. What is an immediate execution function?

The immediate execution function is a function that does not need to be called and can be executed immediately by itself

2. Immediately execute function writing

  1. ( function() { }) ()
(function() {
    
    
    console.log(2)
})();//这个小括号可以看做是调用函数里面可以写实参

(function(a) {
    
    
    cnsole.log(a)// 打印1 a是形参
})(1)// 1为实参 可传递多个参数 中间逗号隔开
  1. (function(){}())
(function(a,b) {
    
    
    console.log(a + b);// 5
}(2,3))

// 函数也可以有名字
(function sum(a,b) {
    
    
    console.log(a + b);
}(1,2))

3. The role of immediate execution function

Create an independent scope, all variables inside are local variables, avoiding the problem of naming conflicts.

Guess you like

Origin blog.csdn.net/qq_46178261/article/details/105316551