Javascript functions like "var foo = function bar() ..."? -


the code goes (the syntax may seem odd far know, there nothing wrong it. or there?)

var add=function addnums(a, b) {                         return a+b;  }                       alert("add: "+ add(2,3));           // produces 5  alert("addnums: "+addnums(2,3));        // should produce 5 

addnums() declared function. so, when pass parameters it, should return result.

then, why not getting second alert box?

you seeing named function expression (nfe).

an anonymous function expression assign function without name variable1:

var add = function () {   console.log("i have no own name."); } 

a named function expression assign named function variable (surprise!):

var add = function addnums() {   console.log("my name addnums, know."); } 

the function's name available within function itself. enables use recursion without knowing "outside name" of function - without having set 1 in first place (think callback functions).

the name choose shadows existing name, if addnums defined elsewhere not overridden. means can use name without fear scoping problems or breaking anything.

in past have used arguments.callee refer function inside without knowing name. support being removed javascript2, nfes correct way nowadays.

here lot of stuff read on topic: http://kangax.github.io/nfe/


1 assigning variable not necessary, serves example distinguish plain function declaration. other context js expects expression (a function argument, example).

2 receive error if have strict mode in effect , try use arguments.callee.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -