Typescript - Global function?

此生再无相见时 提交于 2019-12-20 06:42:09

问题


I'm trying to call a function from a 5-deep nested function in Typescript, and it's not able to see the outside function. Running console.log(this) inside of setTimeout returns the window object.

export class SearchComponent implements OnInit {


lifeCycleFunc(){    //Function 1
    ...

    if() {                //Function 2
        ....

        var.do(item => {        //Function 3
            ....

            var.forEach(var => {      //Function 4
                ...

                setTimeout(function(){    //Function 5

                    this.searchFunc()        //this.searchForAssignments is not a function
                }
            })
        })
    }
}

searchFunc(){
    ...
}


}

回答1:


this context inside setTimeout callback is going to be global object (window), but it should be SearchComponent class for this code to work correctly. To achieve that all nested functions including setTimeout callback should be arrow functions to bind this context correctly:

export class SearchComponent implements OnInit {    
    lifeCycleFunc(){
        ...

        if(condition) {
            ...

            foo.do(bar => {
                ...

                bar.forEach(baz => {
                    ...

                    setTimeout(() => {  
                        this.searchFunc();
                    }, 0);
                });
           });
       }
    }

    searchFunc(){
      ...
    }
}



回答2:


To answer your question and your comment about making it an arrow function, you do this:

setTimeout(() => {  
    this.searchFunc();
}, 0);

instead of:

setTimeout(function() {  
    this.searchFunc();
}, 0);    



回答3:


var.forEach(var => {    //Function 3
            ...

            this.searchFunc()     //TypeError: this.searchForAssignments is not a function
        }.bind(this))

The this reference inside the forEach is the forEach function. You need to bind it to the this reference of the class.



来源:https://stackoverflow.com/questions/47234400/typescript-global-function

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