【问题标题】:Invalid left-hand side in assignment when i want to assign variable JS [duplicate]当我想分配变量JS时,分配的左侧无效[重复]
【发布时间】:2020-11-08 08:41:56
【问题描述】:

当我想更改受损生物的当前 Hp 时,creature.js 中的我的班级攻击返回错误 Invalid left-hand side in assignmentAttackTest.js 是一个单元测试,当我想检查损坏单元的当前马力时。我该如何解决这个错误?

creature.js

import CreatureStatistics from './creatureStatistics.js'

export default class Creature {
    constructor(_name, _attack, _armor, _maxHp, _moveRange) {
        this.stats = new CreatureStatistics(
            (_name || 'Smok'),
            (_attack || 1),
            (_armor || 1),
            (_maxHp || 10),
            (_moveRange || 100))
        this.currentHp = this.stats.getMaxHp();
    }
    attack(_defender, _attacker) {
        _defender.stats.getMaxHp() = _defender.stats.getMaxHp() - _attacker.stats.getAttack() + _defender.stats.getArmor() //<= Invalid left-hand side in assignment
    }
    getCurrentHp() {
        return this.currentHp
    }
}

attackTest.js

import Creature from '../creature.js';

export default class AttackTest {
    creatureShouldLost10HpWhenAttackerHas20AttackAndDefenderHas10Armor() {
        let attacker = new Creature('Attack', 20, 5, 110, 5);
        let defender = new Creature('Defender', 5, 10, 100, 5);

        attacker.attack(defender, attacker)
        if (defender.getCurrentHp() !== 10) {
            throw 'Exception: => Creature nie zadala poprawnie obrazen'
        }
    }
}

creatureStatistic.js

export default class CreatureStatistics {
    constructor(_name, _attack, _armor, _maxHp, _moveRange) {
        this.name = _name;
        this.attack = _attack;
        this.armor = _armor;
        this.maxHp = _maxHp;
        this.moveRange = _moveRange;
    }
    getName() {
        return this.name
    }
    getAttack() {
        return this.attack
    }
    getArmor() {
        return this.armor
    }
    getMaxHp() {
        return this.maxHp
    }
    getMoveRange() {
        return this.moveRange
    }
}

【问题讨论】:

  • 您不能分配给函数/方法调用的结果。您要么需要使用属性本身.maxHp = 42,要么为它创建一个设置器.setMaxHp(42)

标签: javascript


【解决方案1】:

正是因为这一行:

_defender.stats.getMaxHp() = _defender.stats.getMaxHp() - _attacker.stats.getAttack() + _defender.stats.getArmor() //<= Invalid left-hand side in assignment

你可能想把它改成:

this.currentHp = _defender.stats.getMaxHp() - _attacker.stats.getAttack() + _defender.stats.getArmor()

【讨论】:

  • 现在函数返回attacker.attack(defender, attacker) undefined attackTest.js:10 defender.getCurrentHp ƒ getCurrentHp() { return this.currentHp }
  • 你希望它返回什么?
  • 在开始attack生物需要失去一些生命值之后,他的基础生命值是100,然后我想检查他在攻击后有多少生命值getCurrentHp() { return this.currentHp }if (defender.getCurrentHp() !== 90) { throw 'Exception: =&gt; Creature nie zadala poprawnie obrazen' }我需要保存他的生命值攻击后和 this.currentHp 是为了这个
猜你喜欢
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-07
相关资源
最近更新 更多