Do I need to specify parameter in Javascript closure -


<!doctype html> <html> <body>      <p>changing local variable.</p>     <p id="demo"></p>      <script>         var add = (function () { /* need put x in statement?                           "var add = (function(x) { " */                   var counter = 0;                   return function (x) {return counter+=x}         })()          add(10);         add(15);         alert(typeof(add));         document.getelementbyid("demo").innerhtml = add(20);     </script> </body> </html> 

i understand in example above, add assigned return value of self invoking function.

the self-invoking function runs once. sets counter 0 (0), , returns function expression.

my question why function isn't defined like:

var add = (function(x) { .... }() 

because you're not passing in arguments:

//              receive arguments... //                  v var add = (function(x) { .... }() //^ //that pass in here. 

this self invoking function returns function. it's function (the returned function), accepts parameter x.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -