3 回答
TA贡献1859条经验 获得超6个赞
长答案
这是直接从我在一家内部公司写的一篇文章中复制出来的:
for (var i=0; i<10; i++) {
document.getElementById(i).onclick = (function(x){
return function(){
alert(x);
}
})(i);
} function generateMyHandler (x) {
return function(){
alert(x);
}
}
for (var i=0; i<10; i++) {
document.getElementById(i).onclick = generateMyHandler(i);
} var message = 'Hello!';
document.getElementById('foo').onclick = function(){alert(message)};
message = 'Goodbye!'; for (var i=0; i<10; i++) {
document.getElementById('something'+i).onclick = function(){alert(i)};
}i="hello";
for (var i=0; i<10; i++) {
document.getElementById(i).onclick =
(function(x){ /* we use this function expression simply as a factory
to return the function we really want to use: */
/* we want to return a function reference
so we write a function expression*/
return function(){
alert(x); /* x here refers to the argument of the factory function
captured by the 'inner' closure */
}
/* The brace operators (..) evaluates an expression, in this case this
function expression which yields a function reference. */
})(i) /* The function reference generated is then immediately called()
where the variable i is passed */
}TA贡献1155条经验 获得超0个赞
iECMA-/Javascripts function scopelexical scope.
alert(i);5
invoke the outer functionlink.onclick
添加回答
举报
