如何在满足条件时观察某些类变量的变化并执行代码?

时间:2017-11-21 05:51:08

标签: javascript class

我正在编写一个名为Player的javascript类,希望有一些代码可以在Player对象的健康变量低于0时执行,就像写一条消息说玩家已经死了!我不确定如何有效地使用setter来实现这一目标,但我对其他可以完成工作的解决方案持开放态度。我附上了我正在使用的示例代码,我很感激在编写/使用js类时改进技术的解决方案或任何提示。

 class Player {
  constructor(name, health, mana, attack, defense) {  
    this.name = name;
    this.health = health;
    this.mana = mana;
    this.attack = attack;
    this.defense = defense;
  }

  attackPlayer(secondPlayer) {
    secondPlayer.health = secondPlayer.health - this.attack;
    console.log(this.name + " attacks " + secondPlayer.name + " pwnishungly and deals " + this.attack + " in damage." );  
  }
}


var AK = new Player("AK", 100, 200, 60, 100, 2);
var Joe = new Player("Joe", 100, 250, 85, 60, 2);

Joe.attackPlayer(AK);

1 个答案:

答案 0 :(得分:0)

class Player {
  private _health: number
  constructor(name, health, mana, attack, defense) {  
    this.name = name;
    this.health = health;
    this.mana = mana;
    this.attack = attack;
    this.defense = defense;
  }

  get health(){
   return this._health;
  }
  
  set health(value){
    if(value===0) {
      console.log('Player has died!');
    }
    this._health = value;
  }
  
  attackPlayer(secondPlayer) {
    secondPlayer.health = secondPlayer.health - this.attack;
    console.log(this.name + " attacks " + secondPlayer.name + " pwnishungly and deals " + this.attack + " in damage." );  
  }
}