简体   繁体   English

打字稿-全局功能?

[英]Typescript - Global function?

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. 我正在尝试从Typescript中的5个深层嵌套函数调用一个函数,但看不到外部函数。 Running console.log(this) inside of setTimeout returns the window object. 在setTimeout中运行console.log(this)返回window对象。

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(){
    ...
}


}

this context inside setTimeout callback is going to be global object ( window ), but it should be SearchComponent class for this code to work correctly. setTimeout回调内部的this上下文将是全局对象( window ),但是它应该是SearchComponent类,此代码才能正常工作。 To achieve that all nested functions including setTimeout callback should be arrow functions to bind this context correctly: 为了实现包括setTimeout回调在内的所有嵌套函数都应为箭头函数,以正确地绑定this上下文:

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

        if(condition) {
            ...

            foo.do(bar => {
                ...

                bar.forEach(baz => {
                    ...

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

    searchFunc(){
      ...
    }
}

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);    
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. forEach内部的this引用是forEach函数。 You need to bind it to the this reference of the class. 您需要将其绑定到类的this引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM