Saturday 5 October 2019

javascript - Variable inside setTimeout says it is undefined, but when outside it is defined





I have a class. I need to do some http work inside of a timeout. The problem I am faceing is the http variable inside the timeout keeps saying it is undefined.



export class MyClass {

http:Http:


constructor(private http:Http) {
this.http = http;
}

sendFriendRequest(){

this.http.post( ...//http variable is defined here
setTimeout(function(){
this.http.post(... //http is not defined here

}
}
}

Answer



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!


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...