如何通过点击创建“常见”对象?

时间:2018-02-24 15:58:05

标签: javascript

Hello有一个问题,我需要在点击时创建一个“公共对象”配置,以便它可以在其他对象中使用。但是当我创建它时,它在咔嗒声之外是不可见的( 有什么问题以及如何解决它?

这是我的代码

const confirmButton = document.getElementById('confirm');
let gameSettings;

confirmButton.addEventListener('click', e => {
  const countOfPlayers = document.getElementById('player').value;
  const countOfCards = document.getElementById('card').value;
  const countOfNumbers = document.getElementById('nums').value;
  gameSettings = {
    countOfPlayers,
    countOfCards,
    countOfNumbers
  }; // Create object
  e.target.parentElement.remove();
});

class Player {
  constructor(name, cards) {
    this.name = name;
    this.cards = cards || [];
  }
}

class Card {
  constructor(numbers) {
    this.numbers = numbers;
  }
}

class Game {
  constructor() {
    Object.setPrototypeOf(Game, gameSettings); // here it does not see gameSettings, gives out issue Object prototype may only be an Object or null: undefined, this is because gameSettings equal to undefined.
    this.win = false;
  }

  getPlayers() {
    console.log(this.countOfPlayers);
  }
}

JSFiddle - https://jsfiddle.net/ujqe9akL/11/

1 个答案:

答案 0 :(得分:0)

您应该gamesettings prototype Game.prototype,因为Game类的方法放在Game.prototype

class Game {
  constructor() {
    Object.setPrototypeOf(Game.prototype, gameSettings); 
    this.win = false;
  }

  getPlayers() {
    console.log(this.countOfPlayers);
  }
}

我建议不要采用这种方法,尝试制作默认参数或选项,不要将设置放在原型中。