javascript - 实例变量在增量游戏的 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
没有定义,我不知道为什么会出现这种情况,我已经尝试以多种方式修复它,但我无法做到。我真的很困惑为什么会这样。
解决方案
将所有代码包装在 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
in head 标签而不是 body 的末尾,所以这会导致错误,不要不要在 html 中移动代码,仅将 js 代码包装在 window.onload 中。
推荐阅读
- python - 将列时间戳转换为日期时间
- python - 正则表达式:更改 Jenkinsfile 参数定义格式
- php - 如何从 'php://output' 流中读取内容
- java - 集合声明的差异
- windows - Powershell 脚本帮助(通过 SMTP 获取处理和发送输出)
- python - OpenCV 的 RotatedRect 在 Python3 中没有属性“大小”。如何解决这个问题?
- oracle - Oracle SQL 假脱机输出问题 - 标题和破折号
- javascript - 如何在 Javascript 中进行带有 2 位小数的摩卡测试 - 大和小数都给出问题
- c# - 当我打开另一个表单c#时隐藏按钮菜单条
- django - Django - 获取原始请求路径