SetTimeout problem resolution in javascript

  • 2020-03-30 02:54:22
  • OfStack

If you see a problem, it looks something like this.
 
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 will say out of you

This is a pothole, javascript this is generated when called, but it also follows. Here's the solution. I tested it and used call.
 
setTimeout.call(foo(), f.say, 500) 

Some online solutions

This point problem for setTimeout in js

(link: #)

In the end, it's still a question of understanding this.

One day to understand the point to continue to write

Related articles: