【发布时间】:2013-06-15 07:10:17
【问题描述】:
我正在学习 Javascript 中的继承,特别是:寄生组合继承,来自面向 Web 开发人员的专业 JS。我有 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);
}
【问题讨论】:
-
使用
Object.create版本,您不需要重新分配构造函数。 -
@elclanrs - 用于记账以确保 Subtype 的原型和构造函数相互指向
标签: javascript oop inheritance