0

In below example, I need to access this.methodWhichRequredAnywhere() inside functionWhichRequiredInConstructorOnly().

class Example(){

    construtor(){

        function functionWhichRequiredInConstructorOnly(){
             // warning: invalid code
            return this.methodWhichRequredAnywhere + ' complete';
        }

        this.message = functionWhichRequiredInConstructorOnly();
    }

    methodWhichRequredAnywhere(){
        return 'test';
    }
}

Too much explanation about closures in answers to another questions, but I still did not found simple solution to solve above problem.

Note

I understand that above code architecture is contradicting to OOP. Why I used it?

  • I suppose, functionWhichRequiredInConstructorOnly() will be utilized after constructor will be executed. Will methodWhichRequredAnywhere be?
  • I need to group come declarations in my real class. So functionWhichRequiredInConstructorOnly() goes directly below some declarations where it used.
Takesi Tokugawa YD
  • 49
  • 2
  • 16
  • 53

1 Answers1

2

You need to call the function and explicitly set its this value to the value you want. You can do that with .call:

this.message = functionWhichRequiredInConstructorOnly.call(this);

Or define the function as an arrow function as suggested in the comments. Arrow functions don't have their own this binding but resolve it lexically just like any other variable.

Related:

Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072