While I am learning about javascript closure, I ran into an example on w3schools that uses immediately executed functions to provide private variables for functions:
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
but to me, all immediately executed function does is executing the statements in the body, which, if I recall correctly can be accomplished by the keyword new
var add = new function () {
var counter = 0;
return function () {return counter += 1;}
};
document.write("return" + add()+ "<br>"); // return 1
document.write("return" + add() +"<br>"); // return 2, works the same as the example on w3school
new is obviously more complicated, it creates a new object...but I think you are not obligated to use that object (add a return statement at the end).
My question is: what can be done with immediately executed function but not by keyword new? or can you always replace the 1st using the later?