繁体   English   中英

打字稿-全局功能?

[英]Typescript - Global function?

我正在尝试从Typescript中的5个深层嵌套函数调用一个函数,但看不到外部函数。 在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(){
    ...
}


}

setTimeout回调内部的this上下文将是全局对象( window ),但是它应该是SearchComponent类,此代码才能正常工作。 为了实现包括setTimeout回调在内的所有嵌套函数都应为箭头函数,以正确地绑定this上下文:

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

        if(condition) {
            ...

            foo.do(bar => {
                ...

                bar.forEach(baz => {
                    ...

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

    searchFunc(){
      ...
    }
}

要回答您的问题和有关使其成为箭头功能的评论,请执行以下操作:

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

代替:

setTimeout(function() {  
    this.searchFunc();
}, 0);    
var.forEach(var => {    //Function 3
            ...

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

forEach内部的this引用是forEach函数。 您需要将其绑定到类的this引用。

暂无
暂无

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

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