Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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 classvarType = function(name) {
    this.name = name;
};

//our extend functionvar extend = function(cls) {

    //which returns a constructorfunctionfoo() {

        //that calls the parent constructor with itself as scope
        cls.apply(this, arguments)

        //the additional fieldthis.extraField = 1;
    }

    //make the prototype an instance of the old class
    foo.prototype = Object.create(cls.prototype);

    return foo;
};

//so lets extend Type into newTypevar newType = extend(Type);

//create an instance of newType and old Typevar t = newType('bar');
var n = newnewType('foo');


console.log(t);
console.log(t instanceofType);
console.log(n);
console.log(n instanceof newType);
console.log(n instanceofType);

Post a Comment for "How Do I Wrap A Constructor?"