簡體   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