Search code examples
javascriptmethodsfunction-expression

Do double-named methods create side-effects?


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.


Solution

  • 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