typescript 如何从打字稿中的嵌套函数中调用函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41656047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:10:25  来源:igfitidea点击:

How do I call a function from within a nested function in typescript?

javascripttypescript

提问by user3107338

I want to call the function func2from within sample function of function func1. Can someone suggest a way to achieve that?.

我想func2从 function 的示例函数中调用该函数func1。有人可以建议一种方法来实现这一目标吗?

class A
{
   public func1()
   {
     let sample = function()
                  {
                    //call func2... but how?
                  }
   }
   public func2()
   {

   }
 }

Thanks in Advance

提前致谢

回答by Tha'er M. Al-Ajlouni

Use the thiskeyword with the arrowfunction notation like this:

使用this带有arrow函数符号的关键字,如下所示:

class A
{
   public func1()
   {
      let sample = () => 
      {
         this.func2();
      }
   }
   public func2()
   {

   }
 }

The trick is using the arrowfunction, because the arrowfunction changes the definition of thisto be the instance of the classinstead of the current scope.You can read more here

诀窍是使用该arrow函数,因为该arrow函数将 的定义更改this为 的实例class而不是当前范围。您可以在此处阅读更多信息