JavaScript游戏 - 如何自动调用对象的新实例

JavaScript game - how can I call new instances of the object automatically

本文关键字:新实例 实例 对象 游戏 何自动 调用 JavaScript      更新时间:2023-09-26

我正在努力学习JavaScript组合而不是继承,我正在努力解决一些概念。一个是,游戏向用户呈现随机数量的狗,然后提示他们输入有多少只狗。

如果他们做对了,他们会得到一分,然后会看到另一只狗。

我无法弄清楚的是每次如何产生新的狗。以下代码是简化的代码设置:

var dog = function dog(state) {
  return {
    create: function create() {
      console.log('Create the dogs');
      this.dogIsCreated();
    },
    dogIsCreated: function dogIsCreated() {
      console.log('How many dogs do you see?');
    }
  }
}
var questionOne = dog({number: 3}).create();

一旦他们选择了正确的号码,我需要有效地拨打:

var questionTwo = dog({number: 6}).create();

数字本身只是对随机数生成器的调用,但是我将如何自动调用 questionTwo?我什至不知道从哪里开始!

非常感谢!

由于事件而发生"正确"的操作。您需要挂接到此事件,确定真/假,以及何时正确调用dog({number: x}).create();

如果您的需求比这更复杂,请澄清您的问题。谢谢。

使用数组来解决这个问题应该提供更好的可访问性。

var dog = function dog(state) {
  return {
    answer: state.number,
    create: function create() {
      console.log('Create the dogs');
      this.dogIsCreated();
    },
    dogIsCreated: function dogIsCreated() {
      console.log('How many dogs do you see?');
    }
}
var currentQuestion = 0;
var question = [];
function nextQuestion() {
    if (currentQuestion > 0) {
      //to access the last question use question[currentQuestion] e.g. question[currentQuestion].answer
    }
    question.push(dog({number: 6}).create());
    currentQuestion++;
}