【问题标题】:Where is ES2015 function name inference defined?ES2015 函数名称推断在哪里定义?
【发布时间】:2020-03-17 20:43:50
【问题描述】:

我亲眼目睹了这种行为,后来发现了匿名函数(最显着的是新的箭头函数)的“名称推断”概念,但我无法找到这种行为的定义位置。供参考:

// Arrow functions are inherently anonymous so this shouldn't work
const foo = () => {};
console.log(foo.name); // outputs "foo"
const bar = function() {};
console.log(bar.name); // outputs "bar"

// vs

console.log((() => {}).name) // outputs ""
console.log((function() {}).name) // outputs ""

我在MDN 上找到的最接近的东西将其归因于“ECMAScript 2015 中的新功能”。我试图搜索ES2015 spec,但没有成功。这似乎是现代 ES 的一个很大程度上未知但有用的功能,实际上几乎没有文档存在。

谁能为此提供规范规范的参考?

【问题讨论】:

标签: javascript specifications


【解决方案1】:

函数对象下,您会找到name 属性。

使用SetFunctionName 抽象操作将上下文名称分配给该属性,并在规范中的不同位置调用:

1) property declarations 内部对象字面量({ a: b }b 的名称设置为 a,如果 b 是匿名函数)。

2) 在assignments,(如果a 直接是标识符并且b 也是匿名函数,则a = bb 的名称设置为a)。

3) 内部对象destructuring default values(如果b 是匿名函数,则{ a = b } =bs 的名称设置为a)。

4) 在function parameter destructuring 中类似于 3)。

5) variable declarations 与 2) (let a = b; const a = b; var a = b;) 类似。

6) function declarations(包括generator functions (function a() { })。

7) object methods, getters (prefixed with "get") and setters (prefixed with "set") ({ a() { }, get a() {}, set a() {} })。

8) 在class declarationsexpressions (class a {})。

9)binding functions时,被绑定函数接管以“绑定”为前缀的函数名。

请注意,如果出于安全考虑存在计算键或对象属性分配,则不会分配名称。

【讨论】:

  • 该部分没有解释名称推断行为。它说“根据本规范没有与其关联的上下文名称的匿名函数对象没有名称自己的属性,但继承了 %FunctionPrototype% 的名称属性。”但这只是说它继承自Function.prototype.name,即""
  • 但是上下文名称通常与它们相关联
【解决方案2】:

函数的.name 属性是在SetFunctionName procedure 中创建的,它在整个规范中的各个地方都被调用,通常当您分配变量或定义属性并且右侧是匿名函数表达式时。

有关更多讨论,另请参阅 ECMAScript 6's function.name propertyDefinition of name property in assignment expressionWhy does `obj.foo = function() { };` not assign the name `foo` to the function?

【讨论】:

    【解决方案3】:

    @asdfgerte 获胜(最初)(我认为我不能将评论作为答案)。在 spec-speak 中找到但未命名为“名称推断”http://www.ecma-international.org/ecma-262/6.0/index.html#sec-assignment-operators-runtime-semantics-evaluation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-13
      • 2020-01-13
      • 2014-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多