0

下面是寄生组合继承的经典示例。我可以重写inheritPrototype() 如下吗?另外,为什么需要在函数内部设置“构造函数”?

function inheritPrototype(subType, superType){

    subType.prototype = superType.prototype; //assign object
}

经典示例

function object(my_object){
    function F(){}
    F.prototype = my_object;
    return new F();
}

function inheritPrototype(subType, superType){
    var x = object(superType.prototype); //create object
    x.constructor = subType; //augment object
    subType.prototype = x; //assign object
}

function SuperType(name){
    this.name = name;
    this.colors = [“red”, “blue”, “green”];
}

SuperType.prototype.sayName = function(){
    alert(this.name);
};

function SubType(name, age){
    SuperType.call(this, name);
    this.age = age;
}

// ***
inheritPrototype(SubType, SuperType);

SubType.prototype.sayAge = function(){
    alert(this.age);
};
4

0 回答 0