问题
I have a question about context. What is to proper way to deal with context in typescript? If I understand it correctly I have a problem with closures? When I'm calling a function inside a function, which is in object (class) then it's a closure right?
But do I have to use self = this or is there a better way in typescript please? Because I really don't like this solution. And I don't want to bind every little thing.
Example of what I'm tolkien about:
export class SomeClass {
private declaration;
constructor() {}
ngOnInit(){
var self = this;
some code
var interval = setInterval(function() {
self.someFunction();
}, 1000);
}
someFunction() {
something
}
}
Thanks for any advice
回答1:
In this case, you can use the arrow function syntax, which will capture the value of this to refer to the class prototype as you would expect:
ngOnInit() {
some code
var interval = setInterval(() => {
this.someFunction();
}, 1000);
}
回答2:
Besides the arrow function you can use the bind function:
ngOnInit(){
var interval = setInterval(function() {
this.someFunction();
}.bind(this), 1000);
}
or as @IgorRaush stated, this is more elegant:
ngOnInit(){
var interval = setInterval(this.someFunction.bind(this), 1000);
}
Which I prefer in some cases.
来源:https://stackoverflow.com/questions/36876105/how-to-properly-deal-with-scope-in-typescript