递增一个数字并将其附加到函数中

时间:2016-05-03 04:00:28

标签: javascript

我有一个数字作为存储在某个数据库中的计数器。每次页面运行时,计数器的增量都为1.我在检索该数字时没有问题,但我想要的是将该数字附加到某个名称并强制使用新功能。

例如,

newGame0(); newGame1(); newGame2();

我将如何做到这一点?

2 个答案:

答案 0 :(得分:2)

您可以将函数newGame0newGame1newGame2定义为对象的属性,使用括号表示法引用连接counter "newGame" + counter的属性,调用函数

var counter = 0;

var obj = {
  newGame0: function() {
    console.log(counter)
  },
  newGame1: function() {
    console.log(counter)
  },
  newGame2: function() {
    console.log(counter)
  }

}

var interval = setInterval(function() {
  if (counter < 3) {
    // call `newGame0`, `newGame1`, `newGame2`
    obj["newGame" + counter](); 
    ++counter;
  } else {
    clearInterval(interval)
  }
}, 1500)

答案 1 :(得分:-1)

self['newGame' + counter] = function()
{
};

self['newGame' + counter] = existingFunctionName;

考虑在其原型中使用方法编写游戏对象,并在数组中保存一组游戏,而不是弄乱全局命名空间。