Search code examples
javascriptfunctionconstructorargumentsabstraction

Dynamically modifying Constructors in JavaScript?


I'm looking to do something a little bit fancy with constructor functions in Javascript, and I'm not quite sure how to do it.

I want to be able to define Constructor functions, and then pass them into another function (a "modifer") like this:

function OriginalConstructor() {
    // Do constructor things here
    // Like defining methods and properties
}

NewConstructor = modifyConstructor(OriginalConstructor);

And the resulting "NewConstructor" should be functionally equivalent to this:

function NewConstructor(id, data) {
    this.id = id;
    this.data = data;
    // Do stuff from the original constructor here
    // i.e. the same methods and properties defined in the original constructor
}

Does anybody know how to go about creating the "modifyConstructor" function?


Solution

  • You create a function that sets the properties as you defined and calls the original constructor. For example:

    function modifyConstructor(Constr) {
        function NewConstructor(id, data) {
            this.id = id;
            this.data = data;
    
            // Call original constructor
            Constr.apply(this, Array.prototype.slice.call(arguments, 2));
        }
        // Setting the constructor property might not be a good idea depending on
        // the use case
        NewConstructor.prototype = Object.create(Constr.prototype, {
            constructor: {value: NewConstructor, writable: true, configurable: true}
        });
        return NewConstructor;
    }
    

    This basically implements NewConstructor as a subclass of whatever Constr is.