Example of using Anonymous Functions to induce the scope Needed to Create Multiple closure-Using Functions.//An element with an ID of main
var obj=document.getElementById("main");
//An array of items to bind to
var items=["click","keypress"];
//Iterate though each of the items
for(var i = 0;i < items.length; i++){
//use a self-executed anonymous function to induce scope
(function(){
//Remember the value within thi scope
var item=items[i];
//Bind a function to the element
obj["on"+item]=function(){
//item refers to a parent variable that has been successfully
//scoped within the context of this for loop
alert("Thanks for your " + item);
};
})();
}I want to kown the core of the upper code!Thanks.
var obj=document.getElementById("main");
//An array of items to bind to
var items=["click","keypress"];
//Iterate though each of the items
for(var i = 0;i < items.length; i++){
//use a self-executed anonymous function to induce scope
(function(){
//Remember the value within thi scope
var item=items[i];
//Bind a function to the element
obj["on"+item]=function(){
//item refers to a parent variable that has been successfully
//scoped within the context of this for loop
alert("Thanks for your " + item);
};
})();
}I want to kown the core of the upper code!Thanks.
<script>
function func(){
//An element with an ID of main
var obj=document.getElementById("main");
//An array of items to bind to
var items=["click","keypress"];
//Iterate though each of the items
for(var i = 0;i < items.length; i++){
//use a self-executed anonymous function to induce scope
(function(){
//Remember the value within thi scope
var item=items[i];
//Bind a function to the element
obj["on"+item]=function(){
//item refers to a parent variable that has been successfully
//scoped within the context of this for loop
alert("Thanks for your " + item);
};
})();
}
}
</script>
<input type="text" id="main" onclick="func();" />
其实就是给id="main"的那东西。。(这里只是举例。。不一定是文本框)绑定上onkeypress和onclick的方法。当做了那两个动作的时候。。告诉客户端当前是做的onkeypress还是onclick
var items = ["click", "keypress"];
for (var i = 0; i < items.length; i++)
{ (function()
{
var item = items[i];
obj["on" + item] = function()//循环为obj赋上onclick和onkeypress的事件方法
{
alert("Thanks for your " + item); //分别打印Thanks for your click和Thanks for your keypress
};
})();
}
这样做也可以实现。for(var i = 0;i < items.length; i++){
obj["on"+items[i]]=(function(i){
return function(){alert("Thanks for your " + items[i])};
})(i);
}
贴几个链接吧。
ECMAScript 闭包
JS的一个比较奇怪的问题,据说是闭包导致的
理解 JavaScript 闭包我的理解是,传了引用而不是传了值,肯定有所偏差。