Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

   }
 }

Thanks in Advance

like image 437
user3107338 Avatar asked Jan 14 '17 23:01

user3107338


People also ask

Can you call a function within a function in TypeScript?

You can call the same function from within itself in TypeScript. This is called recursion.

How do you call a function inside a function?

To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.

Can we call functions inside of other functions?

Calling a function from within itself is called recursion and the simple answer is, yes.


Video Answer


1 Answers

Use the this keyword with the arrow function notation like this:

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

   }
 }

The trick is using the arrow function, because the arrow function changes the definition of this to be the instance of the class instead of the current scope.You can read more here

like image 109
Tha'er M. Al-Ajlouni Avatar answered Sep 17 '22 19:09

Tha'er M. Al-Ajlouni