gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:36:37 25 4
gpt4 key购买 nike

我正在开发一个用 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] 上的“click”事件时,出现错误无法读取未定义的属性“price”。对我来说,这似乎是在说 this.fishPole 未定义,我不知道为什么会出现这种情况,我已经尝试以多种方式修复它,并且我没能做到。我真的不明白为什么会发生这种情况。

最佳答案

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

关于javascript - 实例变量在增量游戏的 javascript 类中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60476730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com