Reputation: 13286
I am wondering what is the difference between this:
var o = {
name: 'John',
getName: function getName() {
console.log(arguments.callee.name + ' was called');
}
}
o.getName();
To the "regular" anonymous approach:
var o = {
name: 'John',
getName: function () {
console.log('getName was called');
}
}
o.getName();
Because obviously the first one seems to have some benefits... Any downfalls?
Upvotes: 2
Views: 1057
Reputation: 16472
The only difference is that your first example produces a named function and your second example does not. Named functions can be useful when writing error handlers as you can get the name of the function in context. I'm sure there are other uses for them, but I know retrieving the name is not necessarily cross browser friendly so don't bank on this working in every browser.
var myFunctionVar = function test(){
alert(arguments.callee.name);
};
var myFunctionVar2 = function (){
alert(arguments.callee.name);
};
myFunctionVar();
myFunctionVar2();
As RobG and Bergi have pointed out there are issues in using the above code, so please do some more research before using.
Upvotes: 1
Reputation: 664297
Any downfalls?
Yes.
arguments.callee
is deprecated. You should just refer to getName
to get the function object..name
is a non-standard property, don't expect it to work in every browser.I'd go with
var o = {
name: 'John',
getName: function getName() {
console.log('getName was called');
}
};
Where you have a named function (which is beneficial for debugging call stacks), and the log()
works nonetheless.
Upvotes: 2