I am quite new to javascript and i have encounter problems about function call and the closure.
Below are the code that i tried in w3schools,
<!DOCTYPE html>
<html>
<body>
<p>Counting with a local variable.</p>
<button type="button" id="btn">Count!</button>
<p id="demo">0</p>
<script>
var add = (function (test) {
var counter = 0;
return function (test) {return counter += test;}
})();
/*function add(test){
var counter = 0;
return function (test) {return counter += test;}
}*/
function myFunction(){
document.getElementById("demo").innerHTML = add(123);
//document.getElementById("demo").innerHTML = add().call(this, 123);
}
var btn = document.getElementById("btn");
btn.addEventListener("click", myFunction);
</script>
</body>
</html>
It works fine for the current code, that every time i press the button, the number in the paragraph(id="demo") increment by 123.
But when i tried the commented code, which create a function with closure with exact same code, the paragraph value remain at 123 every onclick.
In this situation, i have a few questions to ask.
1.For the code :
var add = (function (test) {...}) ();
What is the usage of the last bracket? If we provide parameter to the last bracket, how can we use it in the declaration of the anonymous function of variable (var add)?
2.Why these two ways to define the function result in different result?
Thanks a lot, any help is appreciated.
EDIT
<!DOCTYPE html>
<html>
<body>
<p>Counting with a local variable.</p>
<button type="button" id="btn">Count!</button>
<p id="demo">0</p>
<script>
/*var add = (function (test) {
var counter = 0;
return function (test) {return counter += test;}
})();*/
function add(test){
var counter = 0;
return function (test) {return counter += test;}
}
function myFunction(){
//document.getElementById("demo").innerHTML = add(123);
document.getElementById("demo").innerHTML = add().call(this, 123);
}
var btn = document.getElementById("btn");
btn.addEventListener("click", myFunction);
</script>
</body>
</html>
It seems that the code run with no error occur, when i use the commented code for declaration of function, but just a bug that the integer of the paragraph didn't increment.