Использование значения свойства класса для воздействия на другой объект класса в зависимости от времени - PullRequest
0 голосов
/ 03 ноября 2019

В настоящее время я пытаюсь научиться использовать классы es6 для приложения, над которым я работаю.

Цель состоит в том, чтобы увеличить возраст животного на основе текущей даты.

Класс животных Animal.js

class Animal {

    constructor(name, age, species, gender, activity, birthday, hunger = 100, stamina = 100, happy = 100) {
        this.name = name;
        this.age = age;
        this.species = species;
        this.gender = gender;
        this.activity = activity;
        this.hunger = hunger;
        this.stamina = stamina;
        this.happy = happy;
        this.birthday = birthday
    }
    birthday() {
        this.age++
        console.log(`Happy birthday to ${this.name}, ${this.name} is now ${this.age}`)
    }
}
module.exports = Animal

Класс времени Time.js

class Time {
    constructor() {
        this.seconds = 0;
        this.minutes = 0;
        this.days = 1;
        this.season = 1;
        this.year = 0;
        this.clock = `${this.minutes}:${this.seconds}`;
        this.monthDate = `${this.season}/${this.days}`
        this.yearDate = `${this.season}/${this.days}/${this.year}`
        this.timeStamp = `${this.season}/${this.days}/${this.year}-${this.minutes}:${this.seconds}`

        // Start timer when 
        this.countTime = setInterval(this.increaseTime.bind(this), 1000)
    }

    increaseTime() {
        this.clock = `${this.minutes}:${this.seconds}`
        this.monthDate = `${this.season}/${this.days}`
        this.yearDate = `${this.season}/${this.days}/${this.year}`
        this.timeStamp = `${this.season}/${this.days}/${this.year}-${this.minutes}:${this.seconds}`

        console.log(this.clock)
        if (this.seconds === 60) {
            this.seconds = 0;
            this.minutes++
            if (this.minutes === 1) {
                this.minutes = 0;
                this.days++
                console.log(this.timeStamp)
                if (this.days === 15) {
                    this.days = 0;
                    this.season++
                    if (this.season > 4) {
                        this.season = 1;
                        this.year++
                    }
                }
            }
        } else {
            this.seconds++
        }
    }

}

module.exports = Time;

Здесь я пытаюсь использовать их оба: Zoo.js

const Animal = require("./Animal");
const Time = require("./Time");

let time1 = new Time();

let gary = new Animal("Gary", 10, "Gorilla", "Male", "Sleeping", '1/2')
if (time1.monthDate === gary.birthday) {
     gary.birthday()
}

Таким образом, основываясь на значении time1.monthDate (которое всегда меняется, потому что у меня есть функция setInterval в классе Time), я выполню функцию в классе Animal, чтобы увеличить возраст Гэри.

IПоймите, что в текущем состоянии мне нужно постоянно запускать эту проверку, поэтому я также попробовал это:

while (time1) {
    if (time1.monthDate === gary.birthday) {
        gary.birthday();
    }
}

Это также не работает, хотя я постоянно запускаю эту проверку.

Любая помощь будет оценена, спасибо заранее!

1 Ответ

1 голос
/ 03 ноября 2019

Это также не работает, хотя я постоянно выполняю эту проверку.

Это потому, что другой код не может быть запущен, пока этот цикл выполняется . Это включает в себя обратный вызов setInterval, который увеличивает время.

Вместо этого, почему бы вам не предоставить способ запланировать обратный вызов на тик таймера:

 class Time {
    constructor() {
      this.seconds = 0;
      this.minutes = 0;
      this.days = 1;
      this.season = 1;
      this.year = 0;
      this.handlers = []; // < collect handlers
      // Start timer when 
    this.countTime = setInterval(this.increaseTime.bind(this), 1000)
    }

    get clock() { // if this is a getter, it is always up to date
      return `${this.minutes}:${this.seconds}`;
    }
    get monthDate() {
       return `${this.season}/${this.days}`;
    }
    get yearDate() {
       return `${this.season}/${this.days}/${this.year}`;
    }
    get timeStamp () {  
        return  `${this.season}/${this.days}/${this.year}-${this.minutes}:${this.seconds}`;
    }

    increaseTime() {
      this.seconds++
      if (this.seconds === 60) {
        this.seconds = 0;
        this.minutes++;
      }
      if (this.minutes === 1) {
         this.minutes = 0;
         this.days++;
      }               
      if (this.days === 15) {
        this.days = 0;
        this.season++
     }
     if (this.season > 4) {
        this.season = 1;
        this.year++
     }

     this.handlers.forEach(h => h(this)); // < trigger handlers
  }

  onTick(h) { this.handlers.push(h); }
}

Тогда вы можете сделать:

time1.onTick(() => {
  if (time1.monthDate === gary.birthday) {
    gary.birthday();
  }
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...