未捕获的TypeError:undefined不是函数

时间:2015-01-15 05:17:47

标签: javascript oop prototype

我是一个相当初学的程序员,所以请原谅我,如果这个解决方案相当简单(尽管我已经很难找到已经发布的解决方案)。我正在尝试面向对象的编程,但在运行程序时得到此错误消息"未捕获的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")

谢谢。

2 个答案:

答案 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)

如果您对 代码不起作用的原因感到好奇,请参阅以下简短说明:

  1. ethan继承自Human.prototype对象。
  2. Human.prototype继承自Object.prototype个实例,因为它是使用对象的创建文字运算符{}创建的。
  3. 因此,当您执行ethan.becomeHuman(..)时,解释程序会检查ethan是否具有属性becomeHuman。它不是。然后它检查继承自ethan的对象Human.prototype上的相同内容。这个版本现在有一个属性becomeHuman,因此通过绑定到this的{​​{1}}关键字来调用它。
  4. 然后在进一步执行中ethanthis.becomeGladiator。现在,ethan.becomeGladiator实例没有名为ethan的属性。它继承自becomeGladiatar实例,它也没有属性Human.prototypebecomeGladiator继承自Human.prototype,其中没有分配属性Object.prototype。您已经检查了整个原型(继承)链但没有成功,这就是您收到错误的原因。