我有一个代码,
var a= document.getElementById("demo");
a.onclick = function(){
alert(this.innerHTML)
setTimeout(function(){
alert(this.innerHTML)
},1000);
}
我从第一个警告语句得到了正确的innerHTML值。但我在第二个警告声明中得到了未定义的值。谁能解释一下呢?
答案 0 :(得分:3)
因为在函数中你有嵌套的函数,并且在嵌套函数中this
关键字将引用窗口。
所以,你可以这样使用:
var a= document.getElementById("demo");
a.onclick = function(){
var that = this;
alert(this.innerHTML)
setTimeout(function(){
alert(that.innerHTML)
},1000);
}
或者,您可以使用绑定方法:
var a= document.getElementById("demo");
a.onclick = function(){
//var that = this;
alert(this.innerHTML)
setTimeout(function(){
alert(this.innerHTML)
}.bind(this),1000); // now this refers to the clicked element
}
答案 1 :(得分:1)
它不正确,this
中的setTimeout
范围限定为window
对象。你必须保存最后一个范围并使用它。比如setTimeout之前的var that = that
:
var a= document.getElementById("demo");
a.onclick = function(){
// save scope
var that = this;
alert(this.innerHTML)
setTimeout(function(){
// since this is a new function, the "this" refers to the window object.
alert(that.innerHTML) // changed "this" to "that"
},1000);
}