WEB Last Wolf
WEB Last Wolf

Reputation: 122

How to use a function that was created inside the constructor?

I'm creating a function inside the constructor, and it needs to be done inside the constructor, I wanted a button to activate it externally, however I have no idea how to do this.

My TypeScript

  private functionActive;

  constructor(){

    this.functionActive = function hello(){

      console.log('Hello world');

    };

    }   

  }

  buttonActive(event){

    this.functionActive.hello();

  }

Upvotes: 1

Views: 57

Answers (3)

Nicholas K
Nicholas K

Reputation: 15443

Two mistakes:

  1. Define the function without the extra )

    constructor() {
       this.functionActive = function hello() {
          console.log("Hello world");
       };
    }
    
  2. Invoke it using the reference of the function i.e. functionActive and not hello, as it is a function expression:

    buttonActive(event) {
       this.functionActive();
    }
    

Upvotes: 3

programoholic
programoholic

Reputation: 5194

If i got your problem right, here is the way to solve it :

private functionActive={};

  constructor(){

    this.functionActive["hello"] = function (){
      console.log('Hello world');
    }
    }   

  buttonActive(event){
    this.functionActive.hello();

  } 

Here is the working demo : demo

Upvotes: 1

xdeepakv
xdeepakv

Reputation: 8135

class A {
  private functionActive;
  constructor(option) {
    if (option.enable)
      this.functionActive = function () {
        console.log("Hello world");
      };
  }
  buttonActive(event) {
    if (typeof this.functionActive === "function") this.functionActive();
  }
}

Upvotes: 0

Related Questions