首页 > 解决方案 > 在 JavaScript 中调用类内部的方法

问题描述

我目前正在学习 JavaScript,并且我编写了一些仅使用基本功能的代码,但现在我正在尝试将我的代码转换为一个类,并且除了 1 件事之外我得到了一切工作。我正在尝试从类中的函数中调用函数:

class Donut {
  constructor(
    donutCountSpan,
    autoClickerPriceSpan,
    autoClickerCountSpan,
    donutMultiplierCountSpan,
    donutMultiplierPriceSpan
  ) {
    this.donutCountSpan = donutCountSpan;
    this.autoClickerPriceSpan = autoClickerPriceSpan;
    this.autoClickerCountSpan = autoClickerCountSpan;
    this.donutMultiplierCountSpan = donutMultiplierCountSpan;
    this.donutMultiplierPriceSpan = donutMultiplierPriceSpan;
    this.donutCount = 200;
    this.donutMultiplierCount = 0;
    this.autoClickerCount = 0;
    this.autoClickerPrice = 100;
    this.donutMultiplierCount = 0;
    this.donutMultiplierPrice = 10;
  }

  activateAutoClickers() {
    setInterval(function () {
      this.donutCount +=
        this.autoClickerCount * Math.pow(1.2, this.donutMultiplierCount);
      this.donutCountSpan.innerText = Math.round(this.donutCount);
    }, 1000);
  }

  buyAutoClicker() {
    if (this.donutCount >= this.autoClickerPrice) {
      this.donutCount -= this.autoClickerPrice;
      this.autoClickerCount += 1;
      this.autoClickerPrice = Math.round(this.autoClickerPrice * 1.1);
      this.donutCountSpan.innerText = Math.round(this.donutCount);
      this.autoClickerPriceSpan.innerText = this.autoClickerPrice;
      this.autoClickerCountSpan.innerText = this.autoClickerCount;
      if (this.autoClickerCount <= 1) {
        this.activateAutoClickers();  //THIS IS THE METHOD THAT ISN'T BEING CALLED
      }
    }
  }

这是我的按钮的事件侦听器:

donut.addEventListener("click", () => {
  donutClicker.addDonut();
});

buyAutoClickerButton.addEventListener("click", ()=> {
  donutClicker.buyAutoClicker();
});

buyDonutMultiplierButton.addEventListener("click",  ()=> {
  donutClicker.buyDonutMultiplier();
});

标签: javascriptencapsulation

解决方案


推荐阅读