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

116
Views
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 answers
Answer question

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 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!