Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have compiled JSX to JavaScript using Babel compiler. Here is the piece of code I'm intrigued with.

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

After compiling JSX to JS, getInitialState is a named method getInitialState(). I couldn't figure out why it isn't a anonymous method.

Original code:

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

Is there any performance advantage writing like this?

like image 415
Anvesh Checka Avatar asked Sep 28 '15 17:09

Anvesh Checka


2 Answers

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.

like image 50
toskv Avatar answered Sep 28 '22 04:09

toskv


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';
like image 30
loganfsmyth Avatar answered Sep 28 '22 04:09

loganfsmyth