Kandarp Gandhi
Kandarp Gandhi

Reputation: 279

Using class functions as arguments in methods NodeJS

I am trying to use a class function as an argument in another methods. But I keep on getting function not defined when trying to do so. Below is how my class looks like:

class Test{
constructor(name){
this.name = name;
    }

functionA(){
    console.log('My name is John');
    }

functionB(){
    console.log('My name is Steve');
    }

}


function caller(args){
    let test = new Test('t1');
  return test.args;
}

caller(functionA())

I am not sure what to do here. Any help is appreciated. Thanks

Upvotes: 1

Views: 56

Answers (2)

9000
9000

Reputation: 40894

(Not an answer, just an explanation.)

There's no top-level functionA, there's functionA defined inside Test. It's an instance method, so it's not even visible in the namespace of Test (Test.functionA is undefined).

In any case, you'd need to pass functionA (a reference to the function), not functionA() (a reference to the result that calling the function produces).

The cleanest method is indeed what @cale_b suggests.

Upvotes: 1

random_user_name
random_user_name

Reputation: 26160

You need to pass the function name (as a string). Currently you are calling functionA(), which is not a defined function.

See the below altered code:

class Test {
  constructor(name) {
    this.name = name;
  }

  functionA() {
    console.log('My name is John');
  }

  functionB() {
    console.log('My name is Steve');
  }

}


function caller(args) {
  let test = new Test('t1');
  // use bracket notation to CALL the function, and include the () to call
  return test[args]();
}

// pass the function name as a string
caller('functionA')

Upvotes: 1

Related Questions