看下面这段顺序
var name = "Bob";
var nameObj ={
name : "Tom",
showName : function(){
console.log(this.name);
},
waitShowName : function(){
setTimeout(this.showName, 1000);
}
};
nameObj.waitShowName();//Bob
nameObj.showName();//Tom
setTimeout函数的默许定义域是全局的,this代指挪用他的谁人对象,showName()函数是个挪用对象为nameObj,故输出了Tom。若要让waitShowName输出Tom,你只需如许做:
var name = "Bob";
var nameObj ={
name : "Tom",
showName : function(){
console.log(this.name);
},
waitShowName : function(){
var that = this; //将this值保留。有些处所也将that写为self。
setTimeout(function(){
console.log(that.name);
}, 1000);
}
};
nameObj.waitShowName();