如何在Javascript对象中定义方法?

时间:2019-06-22 00:45:55

标签: javascript object methods

我是Java的新手,我正在研究一款小型游戏,以更好地处理它。我试图用方法定义一个字符对象,但是由于某种原因,我从我的IDE中收到了奇怪的错误,即“函数语句上的标签'updateHealth',函数声明中缺少名称”。我只是想弄清楚我在做什么错。在我的代码中,显示是角色健康状况在屏幕上的显示方式。

  function Character(display) {
    this.health = 100;
    this.display = display;


    // updates the health on the screen
    updateHealth: function() {
       if(health == 100) {
         this.display.innerText = 'HP: ' + health;
    }
    else if(health > 10 && health < 100) {
      this.display.innerText = 'HP: 0' + health;
    }
    else if(health < 10 && health > 0) {
      this.display.innerText = 'HP: 00' + health;
    }
    else {
      this.display.innerText = 'HP: 000';
    }
  }

  // returns true if character has died
  checkForDeath: function() {
    if(health <= 0) return true;
    else return false;
  }

  // function used when damage is inflicted on
  // a character object
  takeDamange: function(damage) {
    this.health -= damage;
  }

  // handles the four possible moves
  // opponent is null because if player heals
  // then it does not make sense for there to be
  // an opponent
  makeMove: function(move, opponent=null) {
    switch(move) {
      case 'PUNCH':
        opponent.takeDamage(parseInt(Math.random() * 100) % 10);
        opponent.updateHealth();
        break;
      case 'HEAL':
        this.health += 20;
        break;
      case 'KICK':
        opponent.takeDamage(parseInt(Math.random() * 100) % 20);
        opponent.updateHealth();
        break;
      case 'EXTERMINATE':
        opponent.takeDamage(opponent.health);
        opponent.updateHealth();
        break;
    }

    return opponent.checkForDeath();
  }
}

3 个答案:

答案 0 :(得分:1)

可以通过构造函数(例如Character()函数)实例化对象,但是,您需要确保将对象方法(例如updateHealth()等)“附加”到对象的实例角色对象。

一种实现此目标的方法是通过this关键字:

/* Attach the checkForDeath() function as a method of "this" Character instance */
this.checkForDeath = function() {

  /* Accessing "this" corresponds to the instance of the character object */
  if (this.health <= 0) return true;
  else return false;
}

通过进行这些更改,checkForDeath()现在被定义为相应character实例的成员函数。您需要确保通过this访问实例上的字段,如此行if(this.health <= 0) { ... }

所示

您还需要确保像这样通过Character运算符实例化new的实例:

const characterInstance =  new Character( someElement );

这是您的代码的修订版,演示了这种方法:

function Character(display) {
  this.health = 100;
  this.display = display;

  this.updateHealth = function() {
    const health = this.health; /* Add this */
    if (this.health == 100) { 
      this.display.innerText = 'HP: ' + health;
    } else if (health > 10 && health < 100) {
      this.display.innerText = 'HP: 0' + health;
    } else if (health < 10 && health > 0) {
      this.display.innerText = 'HP: 00' + health;
    } else {
      this.display.innerText = 'HP: 000';
    }
  }
  
  this.checkForDeath = function() {
    if (this.health <= 0) return true;
    else return false;
  }

  this.takeDamange = function(damage) {
 
    this.health -= damage;
  }
  
  this.makeMove = function(move, opponent = null) {
    switch (move) {
      case 'PUNCH':
        opponent.takeDamage(parseInt(Math.random() * 100) % 10);
        opponent.updateHealth();
        break;
      case 'HEAL':
        this.health += 20;
        break;
      case 'KICK':
        opponent.takeDamage(parseInt(Math.random() * 100) % 20);
        opponent.updateHealth();
        break;
      case 'EXTERMINATE':
        opponent.takeDamage(opponent.health);
        opponent.updateHealth();
        break;
    }

    return opponent.checkForDeath();
  }
}

const player =  new Character( document.querySelector('p') );
player.takeDamange();
player.updateHealth();
<p></p>

答案 1 :(得分:0)

:更改为=,并将其分配给本地属性,例如

this.updateHealth = function() {
   ...
}

答案 2 :(得分:0)

我建议使用class语法。

class Character {
    constructor(display) {
        this.health = 100;
        this.display = display;
    }

    // updates the health on the screen
    updateHealth() {
        this.display.innerText = `HP: ${Math.max(health, 0).toString().padStart(3, '0')}`;
    }

    // returns true if character has died
    checkForDeath() {
        return health <= 0;
    }

    // function used when damage is inflicted on
    // a character object
    takeDamange(damage) {
        this.health -= damage;
    }

    // handles the four possible moves
    // opponent is null because if player heals
    // then it does not make sense for there to be
    // an opponent
    makeMove(move, opponent = null) {
        switch (move) {
            case 'PUNCH':
                opponent.takeDamage(parseInt(Math.random() * 100) % 10);
                opponent.updateHealth();
                break;
            case 'HEAL':
                this.health += 20;
                break;
            case 'KICK':
                opponent.takeDamage(parseInt(Math.random() * 100) % 20);
                opponent.updateHealth();
                break;
            case 'EXTERMINATE':
                opponent.takeDamage(opponent.health);
                opponent.updateHealth();
                break;
        }

        return opponent.checkForDeath();
    }
}

我也做了一些轻微的重构,这应该使它更容易理解正在发生的事情。