- 事件监听中this的含义
elem.addEventListener(function(){
this
});
对于事件监听中的this全部浏览器指的是当前的监听对象
- setInterval/setTimeout中this的含义
setTimeout(function(){
alert(this);//指的是window
},1000)
- function()函数中this的含义
this.name="lirongfei";//这里的this指的是window
}
当new一个函数的时候,比如上个函数
var obj=new test();
此时的this指的是obj
综合起来运行的时候
也就是在面向对象函数中同时运用其他两种(setTimeout(setInterval),事件监听)this的时候,势必会冲突,解决办法就是将函数的this赋给一个局部变量,以供其他两种调用
function test(){
this.name="lirongfei";
var parentThis=this;
Elem.addEventListerer("click",function(){
alert(parentThis.name);
});
setInterval(function(){
alert(parentThis.name);
},1000);
}
var obj=new test();
这样click的时候取得值就是obj对象的了 而不是window了