使用模板文字更新 JavaScript 类

updating JavaScript classes using template literals

我对 JavaScript classes 的了解有限,我发现很难找到关于它们的好资源来帮助我完成我的项目。

我为回合制游戏创建了以下 classes;

class Player {
    constructor(name, image, location, isTurn) {
      this.name = name;
      this.image = image;
      this.location = location;
      this.isTurn = isTurn;
      this.cssClass = "player";
      this.weapon = "unarmed";
      this.health = 100;
  
      //deal with default weapon here
    }
    // get css class
    getCSSClass() {
        return this.cssClass;
      }
      getPosition() {
          return this.location;
        }
  
      // set position
      setPosition(identifier) {
         this.location = identifier;
         return this.location.toString();
      }
    }
    
  
  let player1 = new Player("player2", "css/player1.png", "", true);
  let player2 = new Player("player2", "css/player2.png", "", false);
  

我还制作了一个功能,可以在棋盘上的随机位置生成玩家。每个图块都有一个唯一的编号 ID(介于 1 和 150 之间)。随机数功能正常。

下面是我遇到问题的生成函数;

function spawnPlayer(n, identifier) {
    let playerSpawn = document.getElementById(identifier);
    playerSpawn = playerSpawn.id;
    console.log(playerSpawn)


    if (occupied.includes(playerSpawn) == true) {

    spawnPlayer(n, identifier);

    } else {
       
   `player${n}`.setPosition(playerSpawn);
    console.log(("player" + `${n}`).getPosition());
    playerArray.shift();
    playerArray.unshift(playerSpawn.id);
    playerSpawn.classList.add("player");
    playerSpawn.classList.add("player" + n.toString());
    //console.log("player" + n);
    //console.log(player2.image);
    playerSpawn.style.setProperty(
        "background-image",
        "url(css/player" + n + ".png)"
    );
    playerSpawn.style.setProperty("background-size", "cover");
    }
}
spawnPlayer(1, randomise());

我无法理解如何使用模板文字,以便我可以为玩家 1 和玩家 2 重新使用此函数作为参数。

`player${n}`.setPosition(playerSpawn);

这是给我带来麻烦的地方。我目前的错误是

Uncaught TypeError: n.setPosition is not a function at spawnPlayer

任何帮助将不胜感激,如果有人可以推荐一些 material 探索 JavaScript class 实施,那将非常有帮助

谢谢

player1player2设置为某个对象的属性。然后你就可以动态访问它们了:

const obj = {
  player1: new Player(...),
  player2: new Player(...),
}

// ...

obj[`player${n}`].setPosition(playerSpawn)