gpt4 book ai didi

javascript - 未捕获的类型错误 : undefined is not a function

转载 作者:行者123 更新时间:2023-12-02 16:35:41 25 4
gpt4 key购买 nike

我是一名相当初级的程序员,所以如果这个问题的解决方案相当简单,请原谅我(尽管我已经努力寻找已经发布的解决方案)。我正在尝试面向对象编程,但在第 14 行运行程序“Uncaught TypeError: undefined is not a function”时收到此错误消息。

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 接受一个父对象并创建一个原型(prototype)为父对象的对象;你只需要简单的对象:

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");

关于javascript - 未捕获的类型错误 : undefined is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27957240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com