user1613229
user1613229

Reputation: 103

How to create a Function that preserve var values?

I have this code

<input type="button" id="buttona" onClick="myFunction('this is buttonA')" />
<input type="button" id="buttonb" onClick="myFunction('this is buttonB')" />
<script>
function myFunction(message) {
  var count=10;
  count = count + 1;
  alert(message + ":" + count);
}
</script>

What I want is when the user click buttonA, show the message "this is buttonA:11", if the user click again buttonA, show "this is buttonA:12", and if the user click buttonB show the message "this is buttonB:11". I don't want to define global counter vars, I wanted "encapsulated" on the function. I.e. if I add:

<input type="button" id="buttonc" onClick="myFunction('this is buttonC')" />;

to have the same functionality without defining almost anything else.

A counter independent each other and preserve the value. Make senses my question?

Thanks in advance

Upvotes: 3

Views: 63

Answers (1)

hugomg
hugomg

Reputation: 69944

You could consider using closures. The basic idea is that instead of having a single "myFunction", you create a function that creates "myFunctions".

function makeCounter(message){
    //We move count outside the onclick handler, so it can increment
    //but its not a global since we are inside another function!
    var count = 10; 
    return function(){
        count = count + 1;
        alert(message + ":" + count);
    };
}

//now use makeCounter to create encapsulated onclick handlers:

document.getElementById("buttona").onclick = makeCounter("This is button A");
document.getElementById("buttonb").onclick = makeCounter("This is button B");

Upvotes: 4

Related Questions