Uncaught TypeError: undefined is not a function

Uncaught TypeError: undefined is not a function

我是一个相当初级的程序员,如果这个问题的解决方案相当简单,请原谅(尽管我已经努力寻找已经发布的解决方案)。我正在尝试面向对象的编程,但是当 运行 程序 "Uncaught TypeError: undefined is not a function" 在第 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")

谢谢。

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. ethan 继承自 Human.prototype 对象。
  2. Human.prototype 继承自 Object.prototype 实例,因为它是使用对象的创建文字运算符 {}.
  3. 创建的
  4. 因此,当您执行 ethan.becomeHuman(..) 时,解释器会检查 ethan 是否有 属性 becomeHuman。它不是。然后它在 ethan 继承自的对象上检查相同的对象,即 Human.prototype。这个现在确实有一个 属性 becomeHuman 所以它被调用 this 关键字绑定到 ethan.
  5. 那么在进一步的执行中this.becomeGladiator就是ethan.becomeGladiator。现在,ethan 个实例没有名为 becomeGladiatar 的 属性。它继承自 Human.prototype 实例,该实例也没有 属性 becomeGladiatorHuman.prototype 继承自 Object.prototype,它都没有分配 属性 becomeGladiatar。您已经检查了整个原型(继承)链但没有成功,这就是您收到错误的原因。