2

我正在学习 Javascript 中的继承,特别是:Parasitic Combination Inheritance,来自 Professional JS for Web Developers。我有 3 种方法将 SuperType 继承到 Subtype 它们的行为方式完全相同。为什么?他们应该吗?我的直觉告诉我我错过了什么

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
}

这是一个辅助函数:

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

下面是使用上述 3 个 inheritPrototype() 函数的代码:

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);
}
4

1 回答 1

1

乍一看,第一个和第二个基本相同(object == Object.create)。在第三个函数中,subType.prototypesuperType.prototype是同一个对象,所以 SuperType 的实例也是 SubType 的实例:

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

myInheritPrototype2(SubType, SuperType); 
console.log(new SuperType() instanceof SubType) // true
于 2013-06-15T07:49:51.050 回答