Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!