Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Invoke a method (not a function) using a string

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

The this context is lost, you need to bind it.

class MyClass {
  constructor() {
    this.foo = 'bar';
  }
  myMethod(param) {
    console.log(param, this.foo);
  }
}

let userInputMethod = 'myMethod';
let userInputParam = 'param';

const myInstance = new MyClass();
const method = myInstance[userInputMethod].bind(myInstance); // bind
method(userInputParam);

Or you could use arrow functions.

class MyClass {
  constructor() {
    this.foo = 'bar';
  }
  myMethod = (param) => {
    console.log(param, this.foo);
  }
}

let userInputMethod = 'myMethod';
let userInputParam = 'param';

const myInstance = new MyClass();
const method = myInstance[userInputMethod]
method(userInputParam);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading