Home > Article > Web Front-end > Characteristic analysis of JS closure
In the body tag, add a u tag with the id node, and there are 5 li tags under the ul tag. How to pop up the li subscript when clicking on different li tags?
1) First you need to get the ul node var node = document.getElementsById('node')
2) Get the child node under the node node var list = node.children
**3) Add onclick to the child node loop Event (note here that there will be closure problems). for(var i=0;i< list.length; i++){
list[i].onclick = function()console.log(i)}}, from the printed results, it is found that each time the output is 7. **
4) Analysis output 7, because i is declared as a global variable using var, pointing to the same address. After the loop is executed, the value of i is 7, so the result printed in each loop is 7
Use two ways to solve it, 1) declare block-level scope variables, and use let j = i every time i is passed in , take over.
let j = i; list[i].onclick = function(){console.log(j)}
In the function method, the block-level variable j is called, and this variable will not be garbage collected. Each for loop points to a different address, so when the click event is triggered, its subscript can be printed correctly. 2) Use closures to solve the problem.
list[i].onclick = function(i){ return function(){console.log(i)}。 }
**Interpretation of closures
A closure is a function that can read the internal variables of other functions. In the JavaScript language, only subfunctions inside a function can read local variables. Closures can be simply understood as "functions defined inside a function". In essence, a closure is a bridge connecting the inside of a function to the outside of the function.
Note: Using closures will cause the variables in the function to be stored in memory, which consumes a lot of memory. Therefore, closures cannot be abused, which will cause performance problems on the web page and may cause memory problems in IE browsers. leakage. . The final solution is to delete all unused local variables before exiting the function.
Use other people’s examples. For your reference
var name = "this window"; var object = { name :"my object", getNameFunc:function () { return function () { return this.name; } } } alert(object.getNameFunc()());/弹出this window2 。此时this对象指向window对象 var object2 = { name: "my object", getNameFunc2: function () { var that = th is; return function () { return that.name; } } } alert(‘that’+object2.getNameFunc2()()); ///弹出my object。此时this对象指向object2对象
Related recommendations:
Simple understanding of JS closures
Detailed explanation of common forms of JS closures
Sample code sharing for JS closure usage
The above is the detailed content of Characteristic analysis of JS closure. For more information, please follow other related articles on the PHP Chinese website!