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

吃可爱长大的小学妹 提交于 2019-12-06 00:16:29

There is no performance hit, except maybe the load time because of the file size.

Naming otherwise anonymous functions helps fixing issues since those names appear in the error stack traces in most browsers.

This video does a good job at explaining what happens when you set names to anonymous functions.

Also this behavious has been included in the ECMA262 ES6 language specification. You can check that here.

The ES6 spec defines many places where the name of an anonymous function is explicitly set, based on the context of the function, even if no function name has been explicitly defined. Here are a bunch of examples.

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';
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!