ECMAScript 6的function.name属性 [英] ECMAScript 6's function.name property

查看:40
本文介绍了ECMAScript 6的function.name属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速提问:此代码的正确结果是什么?

Quick question: what's the correct result for this code:

let f = function(){};
let n = f.name; //"" or "f"?

根据 compat表 n 的值应为"f" .但是, mozilla文档> 说应该返回一个空字符串.哪个是正确的?

According to the compat table, n should have the value "f". However, the mozilla docs say that it should return an empty string. Which one is correct?

推荐答案

由于ECMAScript 6当前处于草稿状态,因此以下答案在将来的某个时候可能会过时.
话虽如此,但引用了 规范草案 :

Since ECMAScript 6 is currently in draft state, the answer below may become outdated sometime in the future.
That being said, referencing the spec draft:

没有上下文名称的匿名函数对象根据此规范与它们相关联的没有自己的名称属性,但继承%FunctionPrototype%的 name 属性.

Anonymous functions objects that do not have a contextual name associated with them by this specification do not have a name own property but inherit the name property of %FunctionPrototype%.

ECMAScript 6 Wiki 读取那

如果无法静态确定名称,例如未分配的匿名函数,则使用空字符串.

If no name can be statically determined, such as in the case of an unassigned anonymous function, then the empty string is used.

但是,

某些函数是匿名的,并且没有名称作为其一部分静态语义.如果函数是直接分配给名称可以静态确定的LHS名称.

Some functions are anonymous and have no name given as part of their static semantics. If the function is directly assigned to a LHS where a name is statically determinable then the LHS name is used.

请注意,规范草案中未提及(也无法直接找到)Wiki提出的声明,但这是合理的假设.

Note that the claims made by the wiki aren't referenced (and can't directly be found) in the spec draft, but they're reasonable assumptions.

如果我们假设这些假设为真,则由于匿名函数已分配给LHS,因此示例函数调用的结果将为"f" .
读取未分配的匿名函数的name属性应该返回一个空字符串.

If we take those assumptions to be true, the result of your sample function call would be "f", since the anonymous function is assigned to a LHS.
Reading the name property of an unassigned anonymous function should return an empty string.

这篇关于ECMAScript 6的function.name属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆