无法弄清为什么我得到统计信息未定义的错误...
我尝试命名和重命名并调用以前命名的函数仍会收到错误
function GameObject(GO){
this.createdAt = GO.createdAt;
this.name = GO.name;
this.dimensions = GO.dimensions;
}
GameObject.prototype.destroy = function(){
return `${this.name} was removed from the game.`;
}
function CharacterStats(stats){
GameObject.call(stats);
this.healthPoints= stats.healthPoints
}
CharacterStats.prototype = Object.create(GameObject.prototype)
CharacterStats.prototype = takeDamage = function(){
return `${this.name} took damage`;
}
function Humanoid(PettyHumans){
this.team = PettyHumans.team;
this.weapons = PettyHumans.weapons;
this.language = PettyHumans.language;
CharacterStats.call(this.PettyHumans)
}
Humanoid.prototype.greet = function(){
return `${this.name} offers a greeting in ${this.language}.`;
}
答案 0 :(得分:0)
此代码将undefined
传递给CharacterStats
:
function Humanoid(PettyHumans){
this.team = PettyHumans.team;
this.weapons = PettyHumans.weapons;
this.language = PettyHumans.language;
CharacterStats.call(this.PettyHumans)
// ^^^^-------------- The problem is here
}
假设您是通过Humanoid
调用new Humanoid
的,那么您还没有在任何地方设置该属性。 PettyHumans
是参数,不是属性。要么将其设置为属性,要么从该行中删除this.
。
旁注:在很多地方,您似乎正在尝试实现类继承(例如,在CharacterStats
和GameObject
之间),但是执行该操作的代码并非如此相当正确。有关如何更正它的方法,请参见this answer(我也写过),可以继续使用ES5语法或使用ES2015 + class
语法。但简单来说,要使其正确的最小更改是添加一行:
GameObject.call(stats);
this.healthPoints = stats.healthPoints
}
CharacterStats.prototype = Object.create(GameObject.prototype)
CharacterStats.prototype.constructor = CharacterStats // Add this (and similar when doing other inheritance)
或者再次使用class
。 (如果需要支持仅ES5的JavaScript引擎,则可以进行翻译。)