2

Was working on some js code performance and saw this approach:

window.sample = {

    foo: function foo(a,b){
       // code goes here
    }

    bar: function bar(a,b){
       // code goes here
    }

}

is there any reason why you would decelerate the function name after the word "function" ?

dose it help to debug?

is it good or bad or just unnecessary?

Endless
  • 29,359
  • 11
  • 97
  • 120
  • @JosephtheDreamer Oh, right. (The "code performance" context was a red herring.) – JJJ May 23 '12 at 13:08

3 Answers3

4

The only reason would be that you can use the function itself from within the function without a reference to the object:

foo: function foo(a,b){
   return a > 0 ? a + foo(a-1,b) : b;
}

Note howeever that support for named function literals is not consistent across browsers, so you should really avoid using it.

Guffa
  • 666,277
  • 106
  • 705
  • 986
1

instead of assigning an anonymous function to the foo and bar properties, they are assigning named functions.

it can be helpful for debugging: the only difference this makes, that i know of, is that you will see the names of the functions show up in the call stack instead of "javascript anonymous function"

jbabey
  • 44,525
  • 12
  • 67
  • 94
0

It's a named function expression. The name of the function is only available as a variable within the function itself. This can be useful for recursion, for example:

var obj = {
    foo: function foo(node) {
        // Do something to node

        var childNode = node.firstChild;
        while (childNode) {
            foo(childNode);
            childNode = childNode.nextSibling;
        }
    }
};

The name of the function is also available in most browsers via the non-standard name property of the function, which can help identify functions while debugging or examining stack traces.

IE < 9 has a flawed implementation, so you need to exercise care when using it. Full details can be found in Juriy Zaytsev's excellent article on the subject.

Tim Down
  • 306,503
  • 71
  • 443
  • 520