1

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

2 Answers 2

1

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')

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

Comments

1

(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.

Comments

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.