Why can't I access the javascript function by its original name after assigning it to another var?

var f=function foo() { console.log("hello"); }; f(); foo(); 

This results in the error: "Exception: ReferenceError: foo not defined"

But "foo" is defined. Why is this happening? I know this is an expression of a function, and "f ()" is used to access this function. But this is not an anonymous function, I have a name for this function. Why can't I access a function using its name?

+5
source share
2 answers

MDN Function Expression

syntax

 var myFunction = function [name]([param1[, param2[, ..., paramN]]]) { statements }; 

The name of the function. May be omitted, in which case the function is anonymous. The name is local to the function body only.

+6
source

You combine function expressions with function declarations.

Declares a variable foo and assigns an anonymous function to it:

 var foo = function() {}; 

Declares a bar function in the current scope:

 function bar() {}; 

Declares a baz variable and assigns a function named qux :

 var baz = function qux() {}; 

Note that in this case, the function is not declared in this area. Only a variable is declared. It so happened that the name property of this function will be set to qux .

See this question .

Edit: code blocks Edit: added appropriate link

+2
source

Source: https://habr.com/ru/post/1265854/


All Articles