一个有效的函数突然"not a function",而 setInterval() 正在运行另一个函数



tl;dr:当我让 setInterval() 每 3 秒运行另一个函数时,我的函数没有运行。

我正在制作一个基于文本的园艺游戏,当我输入植物时运行"plant()"。我还有一个setInterval(updatePlots,3000)。

这两个函数都可以单独工作,但是当我尝试在setInterval()运行时运行plant()时,它会Uncaught TypeError: plant is not a function

(我知道这是setInterval(),因为我在没有运行的情况下测试了种植,它工作正常。

我尝试过(没有奏效):

if (command == "plant") {
  clearInterval(timer);
  plant(a, b);
  var timer = setInterval(updatePlots, 3000);
}

真的不确定我必须显示什么代码,因为这似乎比单行错误更像是一个基本问题......但它就在这里。

function updatePlots() {
  fullplots = [];
  for (i = 0; i < plots.length; i++) {
    if (plots[i].length) {
      fullplots.push(i);
    }
  }
  for (i = 0; i < fullplots.length; i++) {
    plant = plots[fullplots[i]][0];
    status = plots[fullplots[i]][1];
    growth = plots[fullplots[i]][2];
    if (growth < 100) {
        plots[fullplots[i]][2]++;
    }
  }
  if (document.getElementById('plots').style.display == 'block') {
    getPlots();
  }
}
...
function processTwo(command, a) {
  if (command == 'plant') {
    clearInterval(timer);
    console.log('about to plant 1'+a);
    plant(1, a);
    var timer = setInterval(updatePlots, 3000);
  }
  else { createError() }
}

更新:解决了!

function updatePlots() {
  // this way, the global plant function is not overwritten
  // @see JavaScript variable scope
  var plant;
  // You might want to 'var' your other local (?) variables, too
  // var fullplots, i, status, growth;
  fullplots = [];
  for (i = 0; i < plots.length; i++) { //get fullplots
    if (plots[i].length) {
      fullplots.push(i);
    }
  }
  for (i = 0; i < fullplots.length; i++) {
    // at this line of code you overwrite the global plant, which is not a function anymore then
    plant = plots[fullplots[i]][0];
    status = plots[fullplots[i]][1];
    growth = plots[fullplots[i]][2];
    if (growth < 100) { //increment
        plots[fullplots[i]][2]++;
    }
  }
  if (document.getElementById('plots').style.display == 'block') {
    getPlots();
  }
}

问题出现在 setInterval 调用的 updatePlots 方法中。你在那里做的是为"植物"分配一个新值

plant = plots[fullplots[i]][0];

然后,当调用 plant 时,它指向您在 updatePlot 中分配给它的新值,而不是您最初拥有的函数。您必须在 updatePlot 中声明一个新变量,以避免更改植物方法。我会使用不同的名称以避免混淆。

最新更新