this什么时候会出错?
注意:其中var _this = this 的巧妙用法。
1.定时器;
<script type="text/javascript"> //如果面向对象中用了定时器 function Aaa() { var _this = this; this.a=12; // setInterval(this.show,1000)//凡事用定时器调的函数,他的this必然是window。 //解决方法:再套一层,注意用this。 setInterval(function () { _this.show(); },1000) } Aaa.prototype.show = function () { console.log(this.a); } var obj = new Aaa(); obj.show(); </script>
2.事件;
<script type="text/javascript"> function Bbb() { var _this = this;//用this取到对象 this.b=5; //如果面向对象中用了事件 document.getElementById("btn1").onclick = function () { _this.show(); } } Bbb.prototype.show = function () { console.log(this.b); } window.onload = function () { new Bbb(); } </script>