How to properly deal with scope in typescript

烂漫一生 提交于 2019-12-14 01:16:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!