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 h开发者_高级运维ere you cant call otherName()
from anywhere but the body of otherName
itself. From everywhere else you have to use someName()
.
My questions are:
Is there any problem in naming a function different from the var where it's stored?
Does
var a = function a(){}
makes any difference besides just showing the name in the stack trace ?Any other tip/suggestion on this topic :)
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.
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.
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.
精彩评论