Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I 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'd like an instance property, not a class (static/shared) property.

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

The type of Type should not change.

like image 248
Aaron Digulla Avatar asked Apr 11 '12 07:04

Aaron Digulla


1 Answers

update: An updated version here

what you were actually looking for was extending Type into another Class. There are a lot of ways to do that in JavaScript. I'm not really a fan of the new and the prototype methods of building "classes" (I prefer the parasitic inheritance style better), but here's 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);
like image 157
Joseph Avatar answered Nov 13 '22 17:11

Joseph