You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确在构造函数间设置属性?解决this.weapon._getDamage报错问题

解决this.weapon._getDamage is not a function错误的方案

咱们先拆解问题根源:你创建的Weapon实例(比如bow)根本没有_getDamage方法,但Unit的_getDamage方法里却尝试调用this.weapon._getDamage()——这自然会触发报错!

核心修复思路

给Weapon构造函数添加_getDamage方法,让它能返回自身的伤害值,这样Unit的伤害计算逻辑就能正常调用武器的方法了。另外咱们还可以顺便优化Archer的继承逻辑,让代码更规范。

修改后的完整代码

function Weapon(name, damage) {
  this.name = name;
  this.damage = damage;
  
  // 新增_getDamage方法,返回武器自身的伤害值
  this._getDamage = function() {
    return this.damage;
  };

  Object.defineProperty(this, 'toString', {
    value: function () {
      return name + ' damage: ' + damage + " points";
    }
  });
}

var bow = new Weapon('Golden bow', 20);
console.log(bow.toString()); // Golden bow damage: 20 points

function Unit(basicDamage, type) {
  this._basicDamage = basicDamage;
  this._type = type;
  
  this._setWeapon = function (weapon) {
    this.weapon = weapon;
    return this;
  };
  
  this._getDamage = function () {
    // 现在weapon拥有_getDamage方法,调用不再报错
    return (this.weapon ? this.weapon._getDamage() : 0) + this._basicDamage;
  };
  
  this.toString = function () {
    return "Type-" + this._type + ", Have weapon -" + this.weapon + ", hero current damage-" + this._getDamage() + ' points';
  }
}

function Archer(basicDamage) {
  // 明确传递参数给父构造函数,避免参数混乱
  Unit.call(this, basicDamage, "archer");
}

// 优化继承逻辑:让Archer继承Unit的原型方法(后续扩展更方便)
Archer.prototype = Object.create(Unit.prototype);
Archer.prototype.constructor = Archer;

var archer = new Archer(50);
archer._setWeapon(bow);
console.log(archer.toString()); 
// 输出:Type-archer, Have weapon -Golden bow damage: 20 points, hero current damage-70 points

额外说明

  1. 为什么要加_getDamage?:Unit的伤害计算逻辑依赖武器提供自身的伤害值,所以武器必须实现这个方法来保证接口统一——哪怕只是最简单的返回自身damage的逻辑。
  2. 继承优化:原来用Unit.apply(this, arguments)会导致Unit的type参数拿到undefined,改成Unit.call(this, basicDamage, "archer")更清晰。同时设置原型链,让Archer能继承Unit的原型方法,后续扩展功能时更灵活。

内容的提问来源于stack exchange,提问作者Igor Shvets

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:11:40