0

Below is a classic example for Parasitic Combination Inheritance. Can I rewrite inheritPrototype() as the following? Also, why need to set the "constructor" inside the function?

function inheritPrototype(subType, superType){

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

Classic Example

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);
};
user1187968
  • 7,154
  • 16
  • 81
  • 152
  • No, you can't assign the prototype like that. You will just have the same prototype object for both objects. Any change to one would affect the other. Use `subType.prototype = Object.create(super.prototype)` to create a new prototype object that is a copy of the other. – jfriend00 Jun 01 '16 at 00:37
  • "Parasitic inheritance" does mean something entirely different. Please don't use that term. – Bergi Jun 01 '16 at 00:48
  • Your `object` function is totally deprecated. Just use `Object.create` instead, and get a new tutorial/book/whatever. – Bergi Jun 01 '16 at 00:49
  • For your second question (please ask only one per post), see [What it the significance of the Javascript constructor property?](http://stackoverflow.com/q/4012998/1048572) – Bergi Jun 01 '16 at 00:51

0 Answers0