javascript - Storing named function in a variable -


consider piece of code:

var x = function z(){     console.log("called x"); }  x(); // print out "called x" z(); // referenceerror! 

so, possible store named-function inside variable, still can call function variable name.

is there reason behavior? why possible store named-function inside variable? there other scenario in might useful?

when use named function expression (nfe) that, function's name in scope within function:

var x = function z(){      console.log(typeof z); // "function"  };  x();  console.log(typeof z);     // "undefined"

this 1 of big differences between named function expression , function declaration: nfe doesn't add function's name scope in expression appears; declaration does add function's name scope in declaration appears. (they happen @ different times, etc.; rundown of various ways of creating functions , how work in other answer.)

there couple of reasons doing this:

  • it lets function call (via name) without relying on variable, situations recursion useful.

  • in es5 , earlier, gave way give function name (for stack traces , similar). (in es2015+, function have name if use anonymous expression cases; name set based on expression.)

  • in es2015+, lets give function different name 1 inferred expression.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -