javascript - The positions of console.log(typeof(named)); are different. Why does the second one show undefined?
某草草2017-07-05 10:47:50
0
1
690
Why can’t console.log(typeof(named)); located in the global scope access the name of a function expression? After the function is declared, isn’t the name exposed in the global scope? Solution
There are several important differences between function expressions and function declarations:
1. The function declaration will define a variable with the same name, which is the function itself. Function expression only treats the defined function as a value. Even if a name is added after
function
, it will not define the name as a variable. This function expression is a value and can be assigned to other variables.2. You can see that you can write
function()
orfunction c()
in the function expression. Since the latter does not define the variable c in the external scope, what is the difference between them? Simply put There are two points:The d.name in
var d = function c(){}
exists and the value is the string c, while the b.name invar b = function(){}
is undefined.In the internal scope of the function body of
function c(){}
, the variable c exists and is the function itself, which is equivalent to the variable d in the external scope, while the internal scope of the anonymous functionfunction(){}
It can only be referenced using variable b.So this explains the problem that you accessed the named variable in the
function named(){}
function body, but got an undefined variable in the outer scope.