var f=function foo()
{
console.log("hello");
};
f();
foo();
This produces an error as : "Exception: ReferenceError: foo is not defined"
But "foo" is defined. Why does this happen?I know that this is a function expression and "f()" is used to access this function. But this is not an anonymous function , I do have a name for this function. Why am I not able to access the function using its name?
MDN - function expression
syntax
var myFunction = function [name]([param1[, param2[, ..., paramN]]]) {
statements
};
The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.
You are conflating function expressions with function declarations .
This declares a variable foo
and assigns an anonymous function to it:
var foo = function() {};
This declares a function bar
in the current scope:
function bar() {};
This declares a variable baz
and assigns it a function whose name is qux
:
var baz = function qux() {};
Note that in this case, the function is not being declared in this scope. Only the variable is being declared. It just so happens that the name property of this function will be set to qux
.
See this question .
Edit: code blocks Edit: added relevant link
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.