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

118
Vistas
Modify the Constructor Function of a Class

I already have a function for modifing other class methods:

class MyClass {
    constructor() {
        this.num = 1;
    }
    inc(){
        this.num++;
    }
}

runAfterMethod(classHandle, methodName, executeAfter) {
    const oldHandle = classHandle.prototype[methodName];
    classHandle.prototype[methodName] = function () {
        const returnValue = oldHandle.apply(this, arguments);
        //@ts-ignore
        executeAfter.apply(this, arguments);
        return returnValue;
    };
}

runAfterMethod(MyClass, "inc", function() {console.log(this.num)})
new MyClass().inc(); // Prints 2

However, this does not work for the constructor of the class (because it is technically the class itself)

What I would really be happy with is something that mimics this behavior:

class MyClass {
    constructor() {
        this.num = 1;
    }
}

extendConstructor(MyClass, function(){
    this.str = "hello world"
})

new MyClass(); // num: 1, str: "hello world"

I have looked at things like How to modify the constructor of an ES6 class however, they all require = somewhere, which does not work inside of a function (where that only changes the value of the class inside the function, not the class itself)

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Mutating the existing class is really weird. What would be much less of a code smell IMO would be to create a wrapper around the class that instantiates the class, then calls it with your custom callback, and then returns the instance - it'd be a lot more straightforward. Would that work for your purposes?

class MyClass {
    constructor() {
        this.num = 1;
    }
}

const extendConstructor = (theClass, callback) => function(...args) {
  const instance = new theClass(...args);
  callback.call(instance);
  return instance;
};
const Extended = extendConstructor(MyClass, function(){
    this.str = "hello world"
})

console.log(new Extended()); // num: 1, str: "hello world"

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