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
  • 34,080
  • 13
  • 108
  • 131
  • @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
  • 687,336
  • 108
  • 737
  • 1,005
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
  • 45,965
  • 12
  • 71
  • 94
  • Is it not enough if you do console.log(sample); then? – Endless May 23 '12 at 13:09
  • @Endless i think @jbabey meant stack tracing during errors. If it didn't have a name, the console would say something like `anonymous function` since it does not have a name. – Joseph May 23 '12 at 13:11
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
  • 318,141
  • 75
  • 454
  • 536