This article brings you a detailed introduction to the closure principle and examples. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. helped.
Closure
After the function is called, an execution environment and scope chain will be created. The function will be released after it is executed.
After the closure function is executed, the current active variable will be retained in the inner function scope chain, so the inner function can access the outer variable.
(Related tutorial recommendations: js tutorial)
Example 1
What is the printed result?
Example 2
What is the printed result?
The variables declared by var are only Function scope and global scope, the i variable created in this loop will be raised to the top of the function, so the value of the i variable printed by the function is 10
Example 3
The printed result What is it?
#The variable declared by let has block-level scope. Each time the i variable is looped, it is a new i variable, so the myArr array stores Different numbers
Example four
What is the printed result?
This just creates and executes 10 functions, each function An i variable is passed to the parameter j, j stores the variable value, and then prints it out, so the result is 0~9
For more programming related content, please pay attention to php Chinese website Introduction to Programming column!
The above is the detailed content of Closure principles and examples. For more information, please follow other related articles on the PHP Chinese website!