当您查看 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 byFormalParameterListopt
and body specified byFunctionBody
. Pass in theLexicalEnvironment
of the running execution context as the Scope. Pass intrue
as theStrict
flag if theFunctionExpression
is contained instrict
code or if itsFunctionBody
isstrict
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 byFormalParameterListopt
, and body specified byFunctionBody
. Pass in theVariableEnvironment
of the running execution context as the Scope. Pass in true as theStrict
flag if theFunctionDeclaration
is contained instrict
code or if itsFunctionBody
isstrict
code.
我将其解释为声明是否正确
函数 foo(){};
被定义为本质上是在“函数表”中声明的,当加载执行上下文时,它的所有参数和变量都在堆栈上分配,而
函数(){};
在它被解析执行的那一刻之前,它本质上是不存在的,其所有变量和作用域都继承自相关的本地执行上下文?
或者用外行人的话来说,命名声明是预先分配的,而匿名声明是在“运行时”分配的?
最佳答案
这里的重要性不在于命名和未命名函数之间的区别,而在于 FunctionDeclaration
与 FunctionExpression
。
函数声明采用以下形式:
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/