1

I recently ran into a couple of libraries that define methods on objects as follows:

var someObject = {
    myMethod: function myMethod(args){ /* implementation */ }
};

Can someone maybe explain to me what the use of the double naming is? I understand the difference between function someName(){}; and var someName = function(){};, but this setup doesn't make a whole lot of sense to me.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Steven
  • 1,566
  • 2
  • 16
  • 38
  • Well..it's an object initializer (described at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects). – Patrick Nov 02 '14 at 22:07
  • Maybe I didn't explain the question clear enough: I'm wondering why myMethod is both a key in the object definition, as well as a named function through function definition. Is there an advantage to this? – Steven Nov 02 '14 at 22:14
  • You don't have to type someObject.myMethod to call it inside myMethod for instance. – Patrick Nov 02 '14 at 22:14
  • So within the method's own closure you can use it as a shortcut when executing it recursively? That seems like minimal payoff for quite alot of verbosity.. Also: how is that function name carried over into the closure? – Steven Nov 02 '14 at 22:16
  • Obligatory: http://kangax.github.io/nfe/ – Bergi Nov 02 '14 at 23:17

1 Answers1

1

There are several reasons to do this.

  • If you want to refer to the function itself from inside the function it's better to name it than to use arguments.callee (which you can't even use in strict mode)

  • If you console.log the function, you see the name of the method instead of an anonymous function.

  • Error logging is better with named functions, as the name will be added to the stack trace instead of an anonymous entry. Same goes for profiling (cpu / memory)

  • If you assign the method to another object the function name stays the same, even if the property name changes.

There are no "side effects", see the name of the function as an additional "private" var with a reference to the function only accessible from within the function itself and the method name as a "public" property name you can change and use to access it from outside.

It's not the same as the name in a function declaration

var someObject = { 
  publicName:function privateName(){
    someObject.publicName(); // is defined
    privateName(); // is defined
  } 
};
function test() {}

test(); // is defined
privateName(); // is undefined
someObject.privateName(); // also undefined
someObject.publicName(); //is defined
Winchestro
  • 2,138
  • 14
  • 18