2

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?

2
  • 1
    possible duplicate of var functionName = function() {} vs function functionName() {} Commented Oct 9, 2013 at 11:44
  • @Tibos—I don't think it's a duplicate of that questions, which is about function expressions vs function declarations. This question is about named function expressions. Commented Oct 9, 2013 at 12:07

2 Answers 2

2

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.
  • named function expressions cause some problems in quirksy engines

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.

Sign up to request clarification or add additional context in comments.

1 Comment

No, I don't care about them (the problem doesn't really lead to disfunctional code). If you do, you should use a function declaration and then assign that to the property. Have a look at blog.niftysnippets.org/2010/03/anonymouses-anonymous.html
1

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.

Live Demo

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.

1 Comment

There were bugs in IE's implementation of named function expressions that were the basis of them being recommended against for a long time. Maybe they've been fixed in more recent versions, but IE 8 still has a reasonable user share.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.