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
Post a Comment