JavaScript行为 - 函数表达式 vs 函数声明 - 差异

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

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

当在 if( ) 语句中 分配/设置 变量时能够正常工作。

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

我需要知道第一个案例发生了什么,因为第二个案例按预期工作。
有人能解释一下吗?

3
https://kangax.github.io/nfe/ - SLaks
需要看更多的代码。函数f是什么? - Kyle Joeckel
2
@KyleJ。所有的代码都在那里。f函数是 function f() { } - Ivar
1
看起来这个函数无法提升并且消失了。 - Nina Scholz
当使用var g = function f () {}时,同样的原因是f未定义。 - Kevin B
1个回答

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

    };
}

每个函数都定义了自己的作用域(还有全局作用域)。命名函数表达式在其内部创建一个与函数同名的变量,这对于创建递归函数非常有用。(在ES6中,由于语言增加了块级作用域,作用域变得更加复杂,但是这里只涉及函数作用域,因此这不相关。) - Quentin
不,我的意思是函数的外部作用域。(函数的表达式特性,它看起来像一个表达式,这是一个非常好的解释。) - Nina Scholz
也许你应该添加一个参考文献来解释函数表达式和函数声明之间的区别。 - Rashad Saleh
@NinaScholz — 可能有很多作用域在函数外部。但是它在任何一个作用域中都不可用。 - Quentin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接