首页 > 解决方案 > 实例变量在增量游戏的 javascript 类中无法正常工作

问题描述

我正在开发一个用 Javascript 制作的增量游戏,但遇到了一个我不明白的问题。似乎我无法在我的类方法中访问实例变量。

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

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

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

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

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

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

    this.portal = {
      price: 10000000,
      cps: 70000,
      amount: 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没有定义,我不知道为什么会出现这种情况,我已经尝试以多种方式修复它,但我无法做到。我真的很困惑为什么会这样。

标签: javascriptdomfrontendjavascript-objects

解决方案


将所有代码包装在 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 = modulein head 标签而不是 body 的末尾,所以这会导致错误,不要不要在 html 中移动代码,仅将 js 代码包装在 window.onload 中。


推荐阅读