Heim  >  Artikel  >  Web-Frontend  >  javascript中setTimeout的问题解决方法_javascript技巧

javascript中setTimeout的问题解决方法_javascript技巧

WBOY
WBOYOriginal
2016-05-16 16:49:291445Durchsuche

看到一个问题,大概是这个样子得。

复制代码 代码如下:

name = 'out of you'
foo = function(){
this.name = 'xxoo';
}
foo.prototype.say = function(){
console.log(this.name);
}
f = new foo();
f.say(); // 这句会输出xxoo
setTimeout(f.say, 500); // 这句会输出out of you

这是个坑,javascript的this是在调用的时候产生的,还跟上下文有关。这么解决呢。我测试了一下,用了call。
复制代码 代码如下:

setTimeout.call(foo(), f.say, 500)

网上的一些解决方法

js中setTimeout的this指向问题

JavaScript中使用Timer

最后其实还是对this得理解问题。

哪天搞得明白点了再继续写
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn