我对上下文有疑问.处理打字稿中上下文的正确方法是什么?如果我正确理解它,我对闭包有疑问吗?当我在对象(类)中的函数内部调用函数时,那是闭包吗?
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 } }谢谢您的建议
推荐答案在这种情况下,您可以使用箭头函数语法,它将捕获 this 的值以按您期望的那样引用类原型:
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); }更多推荐
如何正确处理打字稿中的范围
发布评论