javascript如何在object中的方法中settimeout调用本方法
Posted On 2016年6月16日
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();
此篇文章已被阅读6092 次
4 Comments
看豪哥的头像,以前也放荡不羁过 ^_^
必须的。
年中快乐!
快乐:)