Hiển thị các bài đăng có nhãn setTimeout. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn setTimeout. Hiển thị tất cả bài đăng

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!

anti-pattern là gì

  Trong công nghệ và lập trình, Anti-pattern (mẫu phản diện) là những giải pháp bề ngoài có vẻ hiệu quả để giải quyết một vấn đề phổ biến, ...