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

How do you get a static reference to a method of a class in JavaScript?

Say I want to pass around a reference to a method of a class in JavaScript:

class Example {
  constructor() {
    this.field = "value"
  }
  exampleMethod() {
    console.log(this.field)
  }
  exampleMethod2() {
    this.field += "."
  }
}

// get references to the methods without having an instance of the object (important detail)
let methods = [Example.exampleMethod, Example.exampleMethod2]  // not correct
let sampledMethod = methods[Math.floor(Math.random()*methods.length)]
let object = new Example()
object.sampledMethod()

Weird example, but say I have more legitimate reasons for wanting these references without an instance of the object. Is there a clean way to do so?

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

>Solution :

The methods exist on the object’s prototype. To call a detached method on an object instance, use .call or .apply:

class Example {
  constructor() {
    this.field = "value"
  }
  exampleMethod() {
    console.log(this.field)
  }
  exampleMethod2() {
    this.field += "."
  }
}

let methods = [Example.prototype.exampleMethod, Example.prototype.exampleMethod2];
let sampledMethod = methods[Math.floor(Math.random() * methods.length)];

let object = new Example();
console.log(object);
console.log('Calling', sampledMethod);
sampledMethod.call(object);
console.log(object);
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