Typescript - 全局函数? [英] Typescript - Global function?

查看:92
本文介绍了Typescript - 全局函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从Typescript中的5层嵌套函数中调用一个函数,但它无法看到外部函数。在setTimeout中运行 console.log(this)返回窗口对象。

 导出类SearchComponent实现OnInit {


lifeCycleFunc(){//函数1
...

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

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

var.forEach(var => {//函数4
...

setTimeout(function(){// Function 5

this.searchFunc()// this.searchForAssignments不是函数
}
})
})
}
}

searchFunc(){
...
}


}


解决方案 c setTimeout 回调将是全局对象( window ),但它应该是 Sear chComponent 类以使此代码正常工作。要实现包括 setTimeout 回调的所有嵌套函数都应该是箭头函数,以正确地绑定 this context:

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

if( (baz => {
...

bar.forEach(baz => {
...

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



searchFunc(){
...
}
}


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


}

解决方案

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

这篇关于Typescript - 全局函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆