<div>1</div> <div>2</div> <script type="text/javascript"> var elements = document.getElementsByTagName("div"); for (var i = 0; i<elements.length; i++) { // elements[i].onclick=function(){ // alert("Div number " + elements[i].innerHTML); //在遍历数组时对DOM监听事件,索引值始终等于遍历结束后的值(数组长度) // } elements[i].onclick = (function(idx) { //闭包,正确显示 return function() { alert("Div number " + elements[idx].innerHTML); } })(i); } for (var i = 0; i<elements.length; i++) { elements[i]._index=i; elements[i].onclick=function(){ alert("Div number " + elements[this._index].innerHTML); } } </script>
用这种方式,也可以在类中替换this
var name="window"; function createFun(){ this.name="obj"; this.getNameFun=function(that){ return function(){ return that.name; }; }(this); } var obj=new createFun(); console.log(obj.getNameFun()); //obj