javascript - JavaScript 中的命名函数与未命名函数以及理解分配

标签 javascript ecmascript-6

当您查看 ECMAScript 6 specification 时,我注意到一些有趣的事情。

13 Function Definition

Syntax

FunctionDeclaration : function Identifier ( FormalParameterListopt ) { FunctionBody }

FunctionExpression : function Identifieropt (FormalParameterListopt ) { FunctionBody }

这两种不同的声明类型进一步分割为以下语义定义:

The production FunctionExpression : function ( FormalParameterListopt ) { FunctionBody } is evaluated as follows:

Return the result of creating a new Function object as specified in 13.2 with parameters specified by FormalParameterListopt and body specified by FunctionBody. Pass in the LexicalEnvironment of the running execution context as the Scope. Pass in true as the Strictflag if the FunctionExpression is contained in strict code or if its FunctionBody is strict code.

还有:

The production FunctionDeclaration : function Identifier ( FormalParameterListopt ) { FunctionBody } is instantiated as follows during Declaration Binding instantiation (10.5):

Return the result of creating a new Function object as specified in 13.2 with parameters specified by FormalParameterListopt, and body specified by FunctionBody. Pass in the VariableEnvironment of the running execution context as the Scope. Pass in true as the Strict flag if the FunctionDeclaration is contained in strict code or if its FunctionBody is strict code.

我将其解释为声明是否正确

函数 foo(){};

被定义为本质上是在“函数表”中声明的,当加载执行上下文时,它的所有参数和变量都在堆栈上分配,而

函数(){};

在它被解析执行的那一刻之前,它本质上是不存在的,其所有变量和作用域都继承自相关的本地执行上下文?

或者用外行人的话来说,命名声明是预先分配的,而匿名声明是在“运行时”分配的?

最佳答案

这里的重要性不在于命名和未命名函数之间的区别,而在于 FunctionDeclarationFunctionExpression

函数声明采用以下形式:

function foo() {...}

注意 function 关键字的位置,前面没有运算符。这种样式被提升到当前上下文的顶部,并且在运行时可用,允许您说出如下内容:

foo();
function foo() {console.log("Foo was called");}

另一方面,如果您在 function 关键字前面放置任何类型的运算符,例如 =(成为函数表达式。函数表达式在求值之前不可用。

foo(); // can't call it it here. `foo` exists due to hoisting, but it is `undefined`
var foo = function() {console.log("foo was called");}
foo();

关于javascript - JavaScript 中的命名函数与未命名函数以及理解分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36814873/

相关文章:

javascript - 导入 es6 模块的最佳方法是什么?

javascript - jS居中功能不适用于页面加载中的一个元素,只需调整大小

javascript - 如何在 es6 中将正则表达式导出为 const?

javascript - ECMA-262 ReturnIfAbrupt

javascript - ES6 promise : how to chain functions with arguments

javascript - 渲染顺序中的 Thunk

javascript - 我如何使用 escape 关闭预览窗口,该窗口将要求用户输入他的名字

javascript - 用于简单 ajax 网站的 Fetch as Google 工具无法正常工作

javascript - jQuery $.each 方法中的 ES6 模板文字

javascript - 为什么我可以使用 this.state 而无需绑定(bind)或使用箭头函数 React