переменные экземпляра не работают правильно в классе javascript для инкрементальной игры - PullRequest
0 голосов
/ 01 марта 2020

Я работаю над добавочной игрой, сделанной в Javascript, и столкнулся с проблемой, которую я не понимаю. Кажется, я не могу получить доступ к переменным экземпляра в моих методах класса.

export default class Store {
  constructor() {
    this.fishPole = {
      price: 50,
      cps: 0.5,
      ammount: 0
    };

    this.net = {
      price: 300,
      cps: 2,
      ammount: 0
    };

    this.boat = {
      price: 2500,
      cps: 15,
      ammount: 0
    };

    this.crew = {
      price: 21000,
      cps: 120,
      ammount: 0
    };

    this.yacht = {
      price: 180000,
      cps: 900,
      ammount: 0
    };

    this.factory = {
      price: 1000000,
      cps: 8000,
      ammount: 0
    };

    this.portal = {
      price: 10000000,
      cps: 70000,
      ammount: 0
    };

    //this creates a list of objects
    this.storeBtns = document.getElementsByClassName("buyBtn");
  }

  store(fishCount) {
    this.storeBtns[0].addEventListener("click", function(price) {
      if (fishCount >= this.fishPole.price) {
        fishCount -= this.fishPole.price;
        console.log("working");
      }
    });
  }
}

и основной файл

 import Store from "/src/store.js";

let fishCount = 0;
let lifeTimeFishCount = 0;
let cps = 0;
//cookies per click
let cpc = 1;

const fishCountSite = document.getElementById("fishCount");
const cpsSite = document.getElementById("fpsCounter");
const goFishing = document.getElementById("fishBtn");
const storeBtns = document.getElementsByClassName("buyBtn");

let store = new Store();

function onClick() {
  fishCount += cpc;
  lifeTimeFishCount += cpc;
  return fishCount;
}

function main() {
  goFishing.addEventListener("click", function() {
    onClick();
    fishCountSite.innerHTML = fishCount;
  });
  store.store(fishCount);
}

main();

Когда я активирую событие 'click' на this.storebtn[0], я получаю ошибку Cannot read property 'price' of undefined. Мне кажется, это говорит о том, что this.fishPole не определено, и я не знаю, почему это так, и я пытался сделать это несколькими способами, чтобы исправить это, и я не смог. Я действительно потерял понимание того, почему это происходит.

1 Ответ

1 голос
/ 01 марта 2020

Оберните весь ваш код в window.onload, кроме импорта Store:

import Store from "/src/store.js";
window.onload = ()=>{

    let fishCount = 0;
    let lifeTimeFishCount = 0;
    let cps = 0;
    //cookies per click
    let cpc = 1;

    const fishCountSite = document.getElementById("fishCount");
    const cpsSite = document.getElementById("fpsCounter");
    const goFishing = document.getElementById("fishBtn");
    const storeBtns = document.getElementsByClassName("buyBtn");

    let store = new Store();

    function onClick() {
      fishCount += cpc;
      lifeTimeFishCount += cpc;
      return fishCount;
    }

    function main() {
      goFishing.addEventListener("click", function() {
        onClick();
        fishCountSite.innerHTML = fishCount;
      });
      store.store(fishCount);
    }

    main();

}

эта ошибка вызвана тем, что ваш документ еще не загружен, поэтому нет никаких элементов, когда ваш код пытается получить элементы, вероятно, у вас есть script type = module в заголовке тега, а не в конце тела, так что это вызывает ошибку, не перемещайте код в html, только оберните ваш код js в window.onload .

...