js函数表达式

var a = function _a() {
            
        }
console.log(_a);
为什么这里   log的时候   会报错???
阅读 2.7k
4 个回答
var a = function _a() {
    console.log(_a);
}
console.log(_a);

有名字的函数表达式的名字_a只在定义的函数体内有效,外面无效

我们把有名字的匿名函数表达式中的函数体称为内联函数,而函数名 _a 只能在这个内联函数的作用域内使用。


ps:为什么叫内联函数,因为如果叫命名匿名函数表达式那特么太别扭了。

console.log(_a);
应该改为console.log(a);

The BindingIdentifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the BindingIdentifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.

根据ECMA-262的说明,函数表达式里面_a可以在函数体内使用,但是在函数外引用不到。

但是,如果写出这样:

function _a() {
}
console.log(_a);

就没有问题了。因为此时是函数声明,不是函数表达式了。

所以,此问题重点是分清函数声明函数表达式的区别。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题