如何正确处理打字稿中的范围 [英] How to properly deal with scope in typescript
问题描述
我对上下文有疑问.处理打字稿中上下文的正确方法是什么?如果我正确理解它,我对闭包有疑问吗?当我在对象(类)中的函数内部调用函数时,那是闭包吗?
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?
但是我必须使用 self = this
还是在打字稿中有更好的方法?因为我真的不喜欢这种解决方案.而且我不想束缚每一件事.
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.
关于托尔金的例子:
export class SomeClass {
private declaration;
constructor() {}
ngOnInit(){
var self = this;
some code
var interval = setInterval(function() {
self.someFunction();
}, 1000);
}
someFunction() {
something
}
}
谢谢您的建议
推荐答案
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);
}
这篇关于如何正确处理打字稿中的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!