简体   繁体   中英

Why do these all these Javascript prototype inheritance methods seem to work the same?

I am learning inheritance in Javascript, specifically: Parasitic Combination Inheritance , from Professional JS for Web Developers. I have 3 methods to inherit SuperType into Subtype They all behave exactly the same way. Why? Should they? My gut tells me I am missing something

function inheritPrototype(subType, superType) {
    var prototype = object(superType.prototype);
    prototype.constructor = subType;
    subType.prototype = prototype;
}

function myInheritPrototype(subType, superType) {
    subType.prototype = Object.create(superType.prototype); // inherit methods
    subType.prototype.constructor = subType; // assign constructor
}

function myInheritPrototype2(subType, superType) {
    subType.prototype = superType.prototype; // inherit methods
    subType.prototype.constructor = subType; // assign constructor
}

Here's a helper function:

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

Here's the code that uses the above 3 inheritPrototype() functions:

function SuperType1(name) {
    this.name = name;
    this.colors = ["r", "g", "b"];
}

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

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

// method inheritance happens only once
inheritPrototype(SubType, SuperType); // works
//myInheritPrototype(SubType, SuperType); // works
//myInheritPrototype2(SubType, SuperType); // also works, but should it?

SubType.prototype.sayAge = function() {
    console.log(this.age);
}

At the first glance, the first and the second are basically the same ( object == Object.create ). In the third function, subType.prototype and superType.prototype are the same object, so instances of SuperType will be also instances of SubType:

function SuperType() {}
function SubType() {}

myInheritPrototype2(SubType, SuperType); 
console.log(new SuperType() instanceof SubType) // true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM