Pass correct “this” context to setTimeout callback

Source: https://stackoverflow.com/questions/36209784/variable-inside-settimeout-says-it-is-undefined-but-when-outside-it-is-defined


The reason for this is that the callback function inside setTimeout is in a different lexical environment. This is why in ES6+ functions can be defined using =>. This is so that the code within a function shares the same scope as the function.
To fix this, you can either use ES6+ syntax, where instead of function(a,b,args) {...} you would use (a,b,args) => {...}:
setTimeout( () => {
  this.http.post(...)
});
or with ES5 syntax:
var root = this;

setTimeout(function(){
    root.http.post(...)
}
Hope this helps!

Không có nhận xét nào:

Cold Turkey Blocker

 https://superuser.com/questions/1366153/how-to-get-rid-of-cold-turkey-website-blocker-get-around-the-block Very old question, but still wan...