How do I wrap a constructor?

前端 未结 1 427
太阳男子
太阳男子 2021-01-18 00:21

I have this JavaScript:

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

var t = new Type();

Now I want to add this:

v         


        
相关标签:
1条回答
  • 2021-01-18 01:06

    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);
    
    0 讨论(0)
提交回复
热议问题