How to wrap a constructor?

I have this javascript:

var Type = function(name) { this.name = name; }; var t = new Type(); 

Now I want to add this:

 var wrap = function(cls) { // ... wrap constructor of Type ... this.extraField = 1; }; 

So, I can do:

 wrap(Type); var t = new Type(); assertEquals(1, t.extraField); 

[EDIT] I would like to have an instance property, not a class property (static / shared).

The code executed in the wrapper function should work as if I had embedded it in a real constructor.

Type must not change.

+5
source share
2 answers

update: Updated version here

what you were actually looking for is an extension of the type to another class. There are many ways to do this in JavaScript. I am not a fan of the new and prototype methods for creating "classes" (I prefer the inheritance style with parasitic inheritance), but here is what I got:

 //your original class var Type = function(name) { this.name = name; }; //our extend function var extend = function(cls) { //which returns a constructor function foo() { //that calls the parent constructor with itself as scope cls.apply(this, arguments) //the additional field this.extraField = 1; } //make the prototype an instance of the old class foo.prototype = Object.create(cls.prototype); return foo; }; //so lets extend Type into newType var newType = extend(Type); //create an instance of newType and old Type var t = new Type('bar'); var n = new newType('foo'); console.log(t); console.log(t instanceof Type); console.log(n); console.log(n instanceof newType); console.log(n instanceof Type); 
+5
source

I do not know how to do it the way you expected, although I admit that it would interest me. I can only think of reassigning the Type variable to a wrapper like this:

 var wrap = function(name) { Type.prototype.constructor.call(this, name); this.extraField = 1; }; wrap.prototype = Type.prototype; Type = wrap; var t = new Type(); assertEquals(1, t.extraField); 
0
source

All Articles