Reputation: 762
I am working with some refactoring of typescripts clases related with dataContext. The thing is yesterday i spent a lot of time trying figure out why i was not getting a breeze.promise from my new datacontext. finally i got the solution and it was related with the scope of "this". Example of bad use of "this":
public getSomething(){
return this.manager.executeQuery(query)
.then(function (data) {
//THIS IS NOT WORKING" INSIDE OF THE FUNCTION
this.log('this log will never be loged :(');
}
}
Now the same code working fine, but using a "that" as temp variable:
public getSomething(){
var that=this;
return this.manager.executeQuery(query)
.then(function (data) {
that.log('get something is complete');
}
}
if you see in abore the second piece of code is working fine, but i have to repeat the process for every method in my class. Now my question is: How can i create a "that" variable at class level? is that possible?
I tried with the code bellow but i am getting a compilation error:"Could not find symbol 'that'."
export class eventDataContext extends dataContextBase.dataContextBase {
public that;
constructor() {
super();
that = this;
...
}
}
any idea how to put this new variable "that" at class level? thank you!
Upvotes: 1
Views: 186
Reputation: 250812
TypeScript has a handy shortcut to solve this problem, called "fat arrow syntax" =>
If you use the following, it should work for you:
getSomething(){
return this.manager.executeQuery(query)
.then((data) => {
this.log('This *will* now be logged :)');
});
}
Quick disclaimer - I'm not sure where your query
is coming from - it isn't passed into the getSomething
method. If it is a class property, use this.query
.
Upvotes: 3