Function in loop and closure
2009-06-30 11:10
260 查看
This article describe the famious issue “function in loop and closure” in JavaScript.
The root cause is loop statements (such as for, while) don’t have their own scope.
Let’s see an example first:
Now, if you click each of the list, all will produce a “You click item 3″ alert
box.
The number 3 comes out of the end execution of the loop (0, 1, 2 and out of the
loop i === 3).
Obviously, the result is not expected.
If you use JSLint to validate this piece of code, you will get the following warning:
Be careful when making functions within a loop. Consider putting the function in
a closure.
According to JSLint’s suggest, we have the first solution:
If you don’t want to create another function, consider using anonymous funtion:
Notice: The self-executing function create a context scope which contains a local
variable i.
When the click event occurs, the variable i is coming from the closure which is
just the self-executing function scope.
There are many ways to solve this problem, following are another three ways:
The root cause is loop statements (such as for, while) don’t have their own scope.
Let’s see an example first:
<ul> <li>Item1</li> <li>Item2</li> <li>Item3</li> </ul>
var liNodes = document.getElementsByTagName("li"); for (var i = 0; i < liNodes.length; i++) { liNodes[i].onclick = function() { alert("You click item " + i); }; }
Now, if you click each of the list, all will produce a “You click item 3″ alert
box.
The number 3 comes out of the end execution of the loop (0, 1, 2 and out of the
loop i === 3).
Obviously, the result is not expected.
If you use JSLint to validate this piece of code, you will get the following warning:
Be careful when making functions within a loop. Consider putting the function in
a closure.
According to JSLint’s suggest, we have the first solution:
// GOOD - 0 function clickNode(liNode, i) { liNode.onclick = function() { alert("You click item " + i); }; } var liNodes = document.getElementsByTagName("li"); for (var i = 0; i < liNodes.length; i++) { clickNode(liNodes[i], i); }
If you don’t want to create another function, consider using anonymous funtion:
// GOOD - 1 var liNodes = document.getElementsByTagName("li"); for (var i = 0; i < liNodes.length; i++) { (function(i) { liNodes[i].onclick = function() { // You click item 0 // You click item 1 // You click item 2 alert("You click item " + i); }; })(i); }
Notice: The self-executing function create a context scope which contains a local
variable i.
When the click event occurs, the variable i is coming from the closure which is
just the self-executing function scope.
There are many ways to solve this problem, following are another three ways:
// GOOD - 2 var liNodes = document.getElementsByTagName("li"); $.each(liNodes, function(i, item) { $(item).click(function() { // You click item 0 // You click item 1 // You click item 2 alert("You click item " + i); }); }); // GOOD - 3 $("li").each(function(i, item) { $(item).click(function() { // You click item 0 // You click item 1 // You click item 2 alert("You click item " + i); }); }); // PREFERED - 4 var liNodes = $("li").click(function(event) { var i = liNodes.index(this); // You click item 0 // You click item 1 // You click item 2 alert("You click item " + i); });
相关文章推荐
- Function in loop and closure(转载)
- Function in loop and closure
- [从jQuery看JavaScript]-匿名函数与闭包(Anonymous Function and Closure)
- 从jQuery看JavaScript]-匿名函数与闭包(Anonymous Function and Closure)
- This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary log
- python closure and function decorators 2
- Oracle 'open cursor loop fetch into' and 'for in cursor loop'
- EF 新增数据时提示it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element
- vue中渲染数据可能有一个无限更新循环--You may have an infinite update loop in a component render function.
- [从jQuery看JavaScript]-匿名函数与闭包(Anonymous Function and Closure)
- const at the end of function and passing const object in a function call
- 【那些年我们一起看过的论文】之《Real-Time Loop Closure in 2D LIDAR SLAM》
- Can we use function on left side of an expression in C and C++?
- A simple visualization of energy function and energy gap in hopfield nets
- Go function closure and recursion
- gevent: AssertionError: Impossible to call blocking function in the event loop callback
- Comparison between overloading operators in member function and in friend function
- [从jQuery看JavaScript]-匿名函数与闭包(Anonymous Function and Closure)【转】
- Unable to update the EntitySet 'T_JsAPI' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
- A Study of Inline View and Analytic Function