javascript如何在object中的方法中settimeout调用本方法

 

function mytest(member)
{
	this.member=member;
	
	this.update=function()
	{
		
		console.log("updated..."+this.member);
		setTimeout(function(){this.update();},2000);	
	}
	

}

new mytest("hi").update();

本段代码是想在object中 循环调用自己的方法。 你会发现

new mytest("hi").update();

只能打印1条updated…hi 日志后,就没有在继续循环调用。 并提示错误。Uncaught TypeError: this.update is not a function

这是什么原因呢?

setTimeout里又执行自己的方法,是通过this关键字。  this丢失的原因,请看 http://alistapart.com/article/getoutbindingsituations
 
代码修改为如下即可。 
 
function mytest(member)
{
	this.member=member;
	
	this.update=function()
	{
		
		var thiz = this; // 这里先将  mytest的this 传给thiz。
		setTimeout(function(){thiz.update();},2000);
		console.log("updated..."+this.member);
	}
	
	

}

new mytest("hi").update();

 

 

此篇文章已被阅读6091 次

4 Comments

liupeng进行回复 取消回复

邮箱地址不会被公开。 必填项已用*标注