未捕获的类型错误:未定义不是一个函数

Uncaught TypeError: undefined is not a function

本文关键字:函数 一个 未定义 类型 错误      更新时间:2023-09-26

我是一个相当初学者的程序员,所以请原谅我,如果这个解决方案相当简单(尽管我已经努力寻找已经发布的解决方案)。我正在尝试面向对象的编程,但是在第 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. 所以当你做ethan.becomeHuman(..)时,解释器会检查ethan是否有属性becomeHuman。它没有。然后,它会在ethan继承自的对象上检查相同的内容,即Human.prototype 。这个现在确实有一个属性becomeHuman因此它被调用this绑定到ethan的关键字。
  4. 然后在进一步的执行中this.becomeGladiator ethan.becomeGladiator.现在,ethan实例没有名为 becomeGladiatar 的属性。它继承自Human.prototype实例,该实例也没有属性becomeGladiatorHuman.prototype继承自Object.prototype,它既没有属性becomeGladiatar赋给它。您已经检查了整个原型(继承)链,但没有成功,这就是您出现错误的原因。