Drostan
Drostan

Reputation: 1839

How can I use the same function for three different variables?

How can I use the same function for three different variables?

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();  

I've tried breaking it down to three separate functions function add20(), function add40() and function add60() but I know this isn't following the DRY approach. Any help would be appreciated!

Upvotes: 0

Views: 169

Answers (2)

Justinas
Justinas

Reputation: 43507

Pass arguments to function making it more dynamic:

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

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

Upvotes: 3

user2693928
user2693928

Reputation:

Pass as parameter:

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

Upvotes: 7

Related Questions