匿名函数与命名函数作为对象键值的区别

Difference between anonymous function vs named function as value for an object key

我已经使用 Babel 编译器将 JSX 编译为 JavaScript。这是我感兴趣的一段代码。

getInitialState: function getInitialState() {
//List out different states that ListComponent could possibly have
return {
  showList: true,
  listType: this.props.type

将JSX编译为JS后,getInitialState是一个命名方法getInitialState()。我不明白为什么它不是匿名方法。

原代码:

getInitialState: function() {
//List out different states that ListComponent could possibly have
return {
  showList: true,
  listType: this.props.type

这样写有性能优势吗?

没有性能影响,除了可能由于文件大小而导致的加载时间。

命名匿名函数有助于解决问题,因为这些名称出现在大多数浏览器的错误堆栈跟踪中。

This 视频很好地解释了将名称设置为匿名函数时会发生什么。

此外,此行为已包含在 ECMA262 ES6 语言规范中。您可以检查 here.

ES6 规范定义了很多地方,在这些地方,根据函数的上下文显式设置匿名函数的名称,即使没有显式定义函数名称也是如此。这里有一堆例子。

12.2.6.9:

var o = {foo: function(){}};
o.foo.name === 'foo';

12.14.4:

var foo;
foo = function(){};
foo.name === 'foo';

12.14.5.2:

var {foo = function(){}} = {};
foo.name === 'foo';

var [foo = function(){}] = [];
foo.name === 'foo';

12.14.5.3:

var foo;
([foo = function(){}] = []);
foo.name === 'foo'

12.15.5.4:

var foo;
({foo = function(){}} = {});
foo.name === 'foo'

13.3.1.4:

let foo = function(){};
foo.name === 'foo'

13.3.2.4:

var foo = function(){};
foo.name === 'foo'

13.3.3.6:

function fn([foo = function(){}]){
    foo.name === 'foo';
}
fn([]);

function fn2({foo = function(){}}){
    foo.name === 'foo';
}
fn2({});

14.1.19:

export default function(){};

import foo from './self'; // Made-up circular ref.
foo.name === 'default';

14.3.9:

var o = {foo(){}};
o.foo.name === 'foo';
class cls {foo(){}};
cls.prototype.foo.name === 'foo';