我正在学习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);
}
答案 0 :(得分:1)
乍一看,第一个和第二个基本相同(object
== Object.create
)。在第三个函数中,subType.prototype
和superType.prototype
是同一个对象,因此SuperType的实例也将是SubType的实例:
function SuperType() {}
function SubType() {}
myInheritPrototype2(SubType, SuperType);
console.log(new SuperType() instanceof SubType) // true