繁体   English   中英

为什么所有这些Javascript原型继承方法似乎都起作用?

[英]Why do these all these Javascript prototype inheritance methods seem to work the same?

我正在学习Javascript中的继承,特别是:Web开发人员专业JS的寄生组合继承 我有3种将SuperType继承为子类型的方法, 它们的行为都完全相同。 为什么? 应该吗 我的肠子告诉我我缺少了一些东西

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 == Object.create )。 在第三个函数中, subType.prototypesuperType.prototype是同一对象,因此SuperType的实例也将是SubType的实例:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM