【发布时间】:2015-08-27 19:14:55
【问题描述】:
出于好奇,我在 Javascript 中使用原型继承和 OOP 继承。大多数结果涉及使用函数模拟“类”和“扩展”概念,而其他结果则使用原型和构造函数。
我写了这段代码:
function Warrior(weaponName) {
var weapon = weaponName;
this.getWeapon = function() {
return weapon;
};
this.setWeapon = function(value) {
weapon = value;
};
this.displayInfo = function() {
return {
"weapon": this.getWeapon(),
};
};
}
function Archer() {
var accuracy = "86%";
this.parent = Archer.prototype; // Inheritance workaround
this.getAccuracy = function() {
return accuracy;
};
this.setAccuracy = function(value) {
accuracy = value;
};
this.displayInfo = function() {
var form = this.parent.displayInfo();
form.accuracy = this.getAccuracy();
return form;
};
}
Archer.prototype = new Warrior("bow");
var w = new Warrior("sword");
var a = new Archer();
console.log(w.displayInfo());
console.log(a.displayInfo());
我这样做是为了在显示来自 Warrior 类的信息时,它会将对象显示为
{ weapon: "sword" }
当显示来自Archer的信息时,对象是:
{ weapon: "sword", accuracy: "86%" }
“子类”从“超类”获取信息并添加到其中。从 Archer 调用“getWeapon()”或“setWeapon”也可以。即使我添加了第三类“Kyudoka”,它扩展了“Archer”并拥有它自己的属性,链条也没有问题。
但是与我在研究时发现的更复杂的代码相比,我觉得这可能是一个幼稚的实现(“继承解决方法”行)并且我遗漏了一些东西(考虑到 JS 有很多微妙之处)。
这是一个理论问题,我没有在任何系统中使用此代码。
【问题讨论】:
-
您可以使用
Object.getPrototypeOf(this)而不是硬编码Archer.prototype作为属性。 -
Warrior 的每个实例创建 3 个函数。因此,例如,如果您有 3 个弓箭手,那么它将产生 300 个功能。通过原型继承,您只创建 3 个函数,无论您有多少实例。这方面可以做一些优化,我不知道。
-
这篇文章帮助了我:JavaScript object creation
-
@WhiteHat - 此类文章的问题在于,它们过于复杂了他们试图向您展示的内容的本质。他为一个敷衍的任务展示了太多的概念。
-
@LyeFish - 谢谢!更少的硬编码总是好的!
标签: javascript oop inheritance prototype