gpt4 book ai didi

javascript - 为什么所有这些 Javascript 原型(prototype)继承方法看起来都一样?

转载 作者:行者123 更新时间:2023-11-30 05:47:34 25 4
gpt4 key购买 nike

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

最佳答案

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

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

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

关于javascript - 为什么所有这些 Javascript 原型(prototype)继承方法看起来都一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17121135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com