On March 12, 2020, “One question of the Day series 🚀” by Wang Ergou blog: Dig gold, think whether, Zhihu, Jane book, CSDN like again, form a habit, one question of the day series will be updated all the time, your support is the biggest motivation for me to continue to share 😘

What is an immediate function?

To be an immediate function, two conditions need to be met:

  • Declare an anonymous function
  • Call this anonymous function immediately

For example, here is a very typical instant-execute function:

(function(){console.log('This is an immediate function.'()))// First declare an anonymous function(function(){console.log(' this is an immediate function '))
// Then the anonymous function is followed by a pair of parentheses () to call the function immediately
Copy the code

What most people don’t understand is why anonymous functions are wrapped in parentheses.

In fact, the purpose of doing this is to be compatible with THE JS syntax.

Instead of using a pair of parentheses, we can use the following syntax:

(function(){alert('I'm an anonymous function'() ()}function(){alert('I'm an anonymous function')}) ()!function(){alert('I'm an anonymous function'(a) +)}function(){alert('I'm an anonymous function'-)} ()function(){alert('I'm an anonymous function'(a) ~)}function(){alert('I'm an anonymous function')} ()void function(){alert('I'm an anonymous function')} ()new function(){alert('I'm an anonymous function')} ()Copy the code

What is the use of executing the function immediately?

There is only one function that executes immediately, and that is to create a separate scope. Prevent variable contamination by making variables inside the scope inaccessible to outsiders.

For example, we could use the immediate-execute function to make the for loop output values from 1 to 6 instead of 6:

for(var i=0; i<6; i++){
  !function(i){// This is the I in the independent scope
        console.log(i)// This is the I in the independent scope
    }
  }(i)// This I is the I in the for loop
}
Copy the code

The reason the code above outputs 1 through 6 instead of 6 sixes is because each time we assign the I in the for loop to the I inside the for loop.

Each time the value of I changes in the for loop, we immediately execute the function to create a separate scope inside the for loop, so the final output is 1 to 6.

Many people will be confused by the I value when they look at this code. In fact, the two I values are not the same.

The following code should make it easier for you:

for(var i=0; i<6; i++){
  !function(j){
    console.log(j)
  }(i)
}
Copy the code

Tell yourself that even if you are tired, don’t forget to learn. There is no shortcut to success, only step by step. ‘!

If there is something wrong in the article, you are welcome to correct it.

Thank you ~ 💘