我是一个相当初学的程序员,所以请原谅我,如果这个解决方案相当简单(尽管我已经很难找到已经发布的解决方案)。我正在尝试面向对象的编程,但在运行程序时得到此错误消息"未捕获的TypeError:undefined不是函数"在第14行。
var Gladiator = Object.create(null);
Gladiator.prototype = {
becomeGladiator: function(attack, defense, hitPoints, name) {
this.attack = attack;
this.defense = defense;
this.hitPoints = hitPoints;
this.name = name;
},
};
var Human = Object.create(Gladiator.prototype);
Human.prototype = {
becomeHuman: function(attack, defense, hitPoints, name) {
this.becomeGladiator(attack, defense, hitPoints, name); //Error here
};
var ethan = Object.create(Human.prototype);
ethan.becomeHuman(14, 12, 15, "Ethan")
谢谢。
答案 0 :(得分:2)
prototype
是函数(构造函数)的一个属性,用于在创建实例时设置内部[[Prototype]]
属性。 Object.create
获取父对象并创建一个对象,其原型是父对象;你只需要普通的物体:
var Gladiator = Object.create(null);
Gladiator.becomeGladiator = function(attack, defense, hitPoints, name) {
this.attack = attack;
this.defense = defense;
this.hitPoints = hitPoints;
this.name = name;
};
var Human = Object.create(Gladiator);
Human.becomeHuman = function(attack, defense, hitPoints, name) {
this.becomeGladiator(attack, defense, hitPoints, name); //Error here
};
var ethan = Object.create(Human);
ethan.becomeHuman(14, 12, 15, "Ethan");
答案 1 :(得分:0)
如果您对 代码不起作用的原因感到好奇,请参阅以下简短说明:
ethan
继承自Human.prototype
对象。Human.prototype
继承自Object.prototype
个实例,因为它是使用对象的创建文字运算符{}
创建的。ethan.becomeHuman(..)
时,解释程序会检查ethan
是否具有属性becomeHuman
。它不是。然后它检查继承自ethan
的对象Human.prototype
上的相同内容。这个版本现在有一个属性becomeHuman
,因此通过绑定到this
的{{1}}关键字来调用它。ethan
是this.becomeGladiator
。现在,ethan.becomeGladiator
实例没有名为ethan
的属性。它继承自becomeGladiatar
实例,它也没有属性Human.prototype
。 becomeGladiator
继承自Human.prototype
,其中没有分配属性Object.prototype
。您已经检查了整个原型(继承)链但没有成功,这就是您收到错误的原因。