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

时间:2018-03-28 20:02:26

标签: javascript

为什么没有为函数f

创建引用

if ( function f() { } ) {
    console.log( typeof f );
}
// result: undefined 

分配/设置变量在if( )

内正常工作

if ( f = 'assigned' ) {
     console.log( typeof f );
}
// result: string

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

有人可以解释一下吗?

1 个答案:

答案 0 :(得分: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

    };
}