views:

121

answers:

3

Say I have the following code:

var f1 = function (a) {
    return f2(a + 1);
};
var f2 = function (a) {
    return f3(a + 1);
}
var f3 = function (a) {
    console.trace();
};

f1(5);

I am doing a console.trace in f3 and this is what the Console is displaying:

Firebug trace


My question is, why is Firebug displaying anonymous instead of the function names during the trace?

+3  A: 

Rewrite it like this to name your functions instead of using anonymous functions:

function f1(a) {
    return f2(a + 1);
};
function f2(a) {
    return f3(a + 1);
}
function f3(a) {
    console.trace();
};

f1(5);

See this page for a good description of the differences between the two syntaxes.

Mark Byers
+2  A: 
function f1(a) {
    return f2(a + 1);
};
function f2(a) {
    return f3(a + 1);
}
function f3(a) {
    console.trace();
};

f1(5);

Would display the function names. Se here for more info.

Fabien Ménager
A: 

Your functions are anonymous functions. For the JavaScript Interpreter f1, f2 and f3 are just variable names. Consider the following code:

var foo = function(a) {
    return f2(a + 1);
};
var f1 = foo;
foo = "bar"

The intepreter and thus FireBug cannot know, whether the function name is foo, f1 or something completely differnt. For the interpreter it is just an anonymous function. You can rewrite your code using named functions like this:

function f1(a) {
    return f2(a + 1);
};

You can even assign the named function to a variable:

var f1 = function f1(a) {
    return f2(a + 1);
};

In this case the function name will always be f1 regardless of the variable's name.

Newer builds of the WebKit and Chrome Inspector support the displayName property on functions 1. If an anonymous function has such a property, the value of the property is used as the function name. In your code you could e.g. write:

var f1 = function(a) {
    return f2(a + 1);
};
f.displayName = "f1".
Fabian Jakobs