Created
August 2, 2014 02:24
-
-
Save imEhllBdPGMVaArZ/56be2f521f8473206144 to your computer and use it in GitHub Desktop.
简单的闭包示例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>闭包示例</title> | |
<script> | |
/* | |
自己的惯性思维写的 | |
比较糟糕的一种方式,在循环中创建了函数,带来无谓的计算,引起混淆, | |
正如书本上改良后的例子,在循环外建立一个辅助函数,让这个辅助函数再返回一个绑定了当前i值的函数,这样就不会导致混淆了 | |
*/ | |
window.onload = function() | |
{ | |
var linkHolder = document.getElementById('links'); | |
var linkItems = linkHolder.getElementsByTagName('a'); | |
console.log(ul +','+ linkItems) | |
for(var i=0;i<linkItems.length;i+=1) | |
{ | |
linkItems[i].onclick = function() | |
{ | |
console.log(this.innerText); | |
return false; | |
}; | |
} | |
} | |
//书本上改良后的例子 | |
var add_the_handlers = function(nodes) | |
{ | |
var helper = function(i) | |
{ | |
return function(e) | |
{ | |
alert(i); | |
}; | |
}; | |
var i; | |
for(i=0;i<nodes.length;i+=1) | |
{ | |
nodes[i].onclick = helper(i); | |
} | |
} | |
</script> | |
</head> | |
<body> | |
<ul id="links"> | |
<li><a href="#">01</a></li> | |
<li><a href="#">02</a></li> | |
<li><a href="#">03</a></li> | |
<li><a href="#">04</a></li> | |
<li><a href="#">05</a></li> | |
</ul> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment