How do I create a function that stores 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 presses button A, it shows the message "this is button A: 11", if the user presses button "A" again, it shows "this is button A: 12", and if the user clicks button "B" , this is button B: 11 ". I don't want to define global counters, I would like to" encapsulate "the function. That is, if I add:
<input type="button" id="buttonc" onClick="myFunction('this is buttonC')" />;
have the same functionality without defining almost anything.
The counter is independent of each other and retains its value. Feels my question?
Thank you in advance
+3
source to share
1 answer
You can use closure. The basic idea is that instead of having one "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");
+4
source to share