实例变量在增量游戏的javascript类中无法正常工作

问题描述 投票:0回答:1

我正在开发使用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();

当我激活this.storebtn[0]上的事件“单击”时,出现错误Cannot read property 'price' of undefined。在我看来,这似乎是在说this.fishPole未定义,我不知道为什么会是这种情况,而且我尝试了多种方法来修复它,但我一直无法这样做。我真的不知道为什么会这样。

javascript dom frontend javascript-objects
1个回答
0
投票

在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中。

© www.soinside.com 2019 - 2024. All rights reserved.