考虑以下代码。
const foo = () => {};
console.log(foo.name); // prints foo
const bar = foo;
console.log(bar.name); // prints foo again
请指出我对 const foo = () => {}; 语句的推理有什么问题。表达式 () => {}
计算结果为匿名函数对象,并且该语句将名称 foo
绑定(bind)到该对象。当然表达式 () => {}
的值不知道它有 name
foo
,但不知何故它知道 foo 之后
与其绑定(bind)。但这是怎么发生的呢?我假设 =
不会改变右侧,并且第 3 行和第 4 行的行为符合我的预期。
最佳答案
根据规范,当 a variable declaration is evaluated并且初始化是一个匿名函数定义,然后该定义以特殊方式进行计算,传递要用作函数名称的变量名称:
LexicalBinding : BindingIdentifier Initializer
1. Let bindingId be StringValue of BindingIdentifier.
2. Let lhs be ! ResolveBinding(bindingId).
3. If IsAnonymousFunctionDefinition(Initializer) istrue
, then
a. Let value be ? NamedEvaluation of Initializer with argument bindingId.
...
评估赋值表达式时会发生类似的情况。
关于javascript - 匿名函数如何知道它的名字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73804138/