Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

126
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda