【问题标题】:Why do these all these Javascript prototype inheritance methods seem to work the same?为什么所有这些 Javascript 原型继承方法看起来都一样?
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢@thg435。将两个原型等同起来确实会产生这个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-06
  • 1970-01-01
  • 2015-03-19
  • 2021-12-04
  • 2015-10-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多