22

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

5
  • 1
    this.func2()? Commented Jan 14, 2017 at 23:16
  • 1
    @Benjamin: Depends on what this refers to inside sample (i.e. how sample is called). Commented Jan 14, 2017 at 23:20
  • nop....scope of this is only in func1...not within sample(nested) function. Commented Jan 14, 2017 at 23:23
  • Related: How to access the correct this inside a callback? Commented Jan 14, 2017 at 23:27
  • Thank a lot Felix for the link. :) Commented Jan 14, 2017 at 23:33

1 Answer 1

47

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

Sign up to request clarification or add additional context in comments.

6 Comments

That depends on what this refers to inside sample.
I updated the answer to fix that by using an arrow function that will use the correct scope.
Awesome.......that works.......could you please explain me how it works?
Its an anonymous function i believe.....but then how is it different from named function......would appreciate if you provide me any link that explains it. Thank you once again.
@user3107338: Because arrow functions don't have their own this. See stackoverflow.com/q/28371982/218196 and stackoverflow.com/q/34361379/218196 .
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.