如何对三个不同的变量使用相同的函数?

时间:2016-11-17 09:19:31

标签: javascript

如何对三个不同的变量使用相同的函数?

var game = {score:0},

scoreDisplay = document.getElementById("score1");

function add20() {
  TweenLite.to(game, 1, {score:"+=20", roundProps:"score", onUpdate:updateHandler, ease:Linear.easeNone});
}

function updateHandler() {
  scoreDisplay.innerHTML = game.score;
}

add20();  

我已尝试将其分解为三个单独的函数function add20()function add40()function add60(),但我知道这不符合DRY方法。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:7)

作为参数传递:

function add(n) {
  TweenLite.to(game, 1, {score:"+=" + n, roundProps:"score", onUpdate:updateHandler, ease:Linear.easeNone});
}
add(20);
add(40);
add(60);

答案 1 :(得分:3)

将参数传递给函数使其更具动态性:

function addScore(score) {
    TweenLite.to(game, 1, {score:"+="+score, roundProps:"score", onUpdate:updateHandler, ease:Linear.easeNone});
}

addScore(20);
addScore(40);
addScore(60);