如何对三个不同的变量使用相同的函数?
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方法。任何帮助将不胜感激!
答案 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);