Reputation: 653
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?
Upvotes: 1
Views: 87
Reputation: 816252
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.
Upvotes: 3
Reputation: 1154
Your example looks like a bad practice.
This way it is much easier to maintain,
I'd go like so:
function OriginalConstructor(id, number){
this.id = id;
this.number = number;
}
var Obj = new OriginalConstructor();
function newConstructor(Obj){
this.id = Obj.id;
this.number = Obj.number * 2;
}
newObject = new newConstructor(Obj);
What you receive from that is: an Obj that was originally created by original constructor, and it's data and state never changed and a newObject which was created by the modifiedConstructor which modifies an object based on a new constructor.
Upvotes: 0