我正在学习 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);
}