//实现点击第i个div时仅alert该div对应的i值;
var divs = document.getElementsByTagName("div");
for(var i=0;i<divs.length;i++){
divs[i].onclick =(function(i){
return function(e){
alert(i);
window.event ? window.event.cancelBubble = true : e.stopPropagation();
}
})(i)
}
//考察this绑定。
function test(){
this.msg = "hi";
msg ="hello";
this.test = function(){
this.msg = "yaya";
msg = "haha"
alert(this.msg);
}
return this;
}
new test().test(); //yaya
test().test();//haha
2009-6-26日更新:今天偶然看到第一题另外的解法,确实不错:[url]http://xkr.us/js/closures[/url]
function setListeners(elements) {
for (var i=0;i<elements.length;i++) {
elements[i].idx=i;
elements[i].onclick=function () { alert(this.idx); };
}
}