【问题标题】:Stats not defined未定义统计信息
【发布时间】:2019-05-24 15:43:28
【问题描述】:

无法弄清楚为什么我会收到未定义统计信息的错误...

我尝试过命名和重命名,调用之前命名的函数仍然报错

    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}.`;
    }

【问题讨论】:

  • 在哪里您遇到此错误? (上面哪一行。)

标签: javascript this prototype operator-keyword


【解决方案1】:

此代码将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
}

假设您通过new Humanoid 调用Humanoid,您还没有在任何地方设置该属性。 PettyHumans 是一个参数,而不是一个属性。将其设置为属性,或从该行中删除 this.


旁注:在一些地方,您似乎正在尝试实现类类继承(例如,在CharacterStatsGameObject 之间),但这样做的代码并不完全 正确。请参阅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-only JavaScript 引擎,你可以转译。)

【讨论】:

  • 你是炸弹 T.J.打算试试,然后回复你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-28
  • 2017-11-14
  • 2015-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多