Note to dup finders: please feel free to mark this as a dup if the dup shows how to solve with classes and methods, not just functions.
I'm building a command line tool that solicits string input from the user then tries to invoke a class with matching methods and params. How do I call so that this is defined?
I have a class:
class MyClass {
constructor() {
this.foo = 'bar';
}
myMethod(param) {
console.log(param, this.foo); // this is undefined, based on how I invoke it
}
}
I'd like to do this, once I get the user input...
let userInputMethod = 'myMethod';
let userInputParam = 'param';
const myInstance = new MyClass();
const method = myInstance[userInputMethod];
method(userInputParam); // error, because I need somehow to set the context of this