search

Home  >  Q&A  >  body text

javascript - The positions of console.log(typeof(named)); are different. Why does the second one show undefined?

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

某草草某草草2690 days ago821

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-07-05 10:49:50

    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.

    function a(){} // 函数声明,同时在外部作用域定义了可以使用的变量a
    var b = function(){} //函数表达式,匿名函数是一个值,赋值给了变量b
    var d = function c(){} //函数表达式,函数本身是一个值,没有在外部作用域定义变量c,但赋值给了变量d。

    2. You can see that you can write function() or function 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 in var 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 function function(){} 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.

    reply
    0
  • Cancelreply