Home  >  Article  >  Web Front-end  >  Solution to the problem of setTimeout in javascript_javascript skills

Solution to the problem of setTimeout in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:49:291447browse

I saw a problem that probably looked like this.

Copy code The code is as follows:

name = 'out of you'
foo = function(){
this.name = 'xxoo';
}
foo.prototype.say = function(){
console.log(this.name);
}
f = new foo();
f.say(); // This sentence will output xxoo
setTimeout(f.say, 500); // This sentence will output out of you

This is a pitfall. JavaScript's this is generated when it is called, and it is also related to the context. This is how to solve it. I tested it and used call.
Copy code The code is as follows:

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

Some solutions on the Internet

This points to the problem of setTimeout in js

Using Timer in JavaScript

In the end, it’s still a matter of understanding this.

I can continue writing when I understand it better one day
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn