Pablo Fernandez
Pablo Fernandez

Reputation: 105220

anonymous and named functions doubt

While debugging I found that this kind of functions:

var f = function() {};

Appear on the stack trace of firebug or webkits dev console as anonymous, and rightfully so.

Also I've seen people defining these as:

var someName = function otherName(){};

Which are quite weird. Note that here you cant call otherName() from anywhere but the body of otherName itself. From everywhere else you have to use someName().

My questions are:

Upvotes: 2

Views: 371

Answers (3)

katspaugh
katspaugh

Reputation: 17899

Note that here you cant call otherName() from anywhere but the body of otherName itself.

Not in IE (including IE8).

See http://kangax.github.com/nfe/#jscript-bugs for more named function bugs, very nice article.

Upvotes: 1

brymck
brymck

Reputation: 7663

Not really. With var a = function b() {} the named function isn't hoisted and its prototype is not meaningfully modifiable. Take the following code for example:

function foo() {
}
foo.prototype.bar = "hi";

var a = new foo();         // this inherits from function foo() above
var b = function foo() {}; // this has nothing to do with the above

console.log(a.bar); // returns "hi" due to inheritance
console.log(b.bar); // returns undefined; its prototype is a new named
                    // function

var c = function() {};
var d = function d() {};

console.log(c.name); // returns ""
console.log(d.name); // returns "d"

AFAICT, the main useful method is having the name easily accessible (mostly for the var a = function a(){} form), which might be helpful in some edge cases, I'd think mostly in error handling.

Upvotes: 0

Ray Toal
Ray Toal

Reputation: 88378

There's no problem with assigning a function named f to a variable named a.

A nice reference on functions is https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope. Of particular interest is the section entitled "Function constructor vs. function declaration vs. function expression" which has a detailed discussion the on distinction between the function name and the variable the function is assigned to. (You may have seen this already.)

My guess is the reason that the debugger prints something like

var a = function a() {}

is that the function's name appears when the function value itself is serialized. The debugger is giving you all the information it has.

Upvotes: 3

Related Questions