javascript行为 - 函数表达式与函数声明 - 差异

ano*_*ous 4 javascript

为什么没有为函数创建引用f

if ( function f() { } ) {
    console.log( typeof f );
}
// result: undefined 
Run Code Online (Sandbox Code Playgroud)

分配/设置变量正常工作内if( )

if ( f = 'assigned' ) {
     console.log( typeof f );
}
// result: string
Run Code Online (Sandbox Code Playgroud)

我需要知道在第一种情况下会发生什么,因为第二种情况正如预期的那样工作

有人可以解释一下吗?

Que*_*tin 7

由于您已放入function f() { }表达式上下文,因此它是一个命名函数表达式而不是函数声明.

这意味着,当它创建了一个函数,并且该函数具有名称f,它创建具有名称的变量f 在函数(本身)的范围,而不是在其中创建的功能的范围.

// Global scope
function a() {
// a is a function declaration and creates a variable called a to which the function is assigned in the scope (global) that the declaration appears in
    function b() {
    // b is a function declaration and creates a variable called a to which the function is assigned in the scope (function a) that the declaration appears in
    }
    var c = function d() {
    // c is a variable in the scope of the function b. The function d is assigned to it explicitly
    // d is a function expression and creates a variable called d to which the function is assigned in the scope (function d) of itself

    };
}
Run Code Online (Sandbox Code Playgroud)