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?

thSoft
  • 21,755
  • 5
  • 88
  • 103
Guy
  • 12,488
  • 16
  • 79
  • 119
  • 1
    possible duplicate of [var functionName = function() {} vs function functionName() {}](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) – Tibos Oct 09 '13 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. – RobG Oct 09 '13 at 12:07

2 Answers2

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 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 http://blog.niftysnippets.org/2010/03/anonymouses-anonymous.html – Bergi Oct 09 '13 at 12:30
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.

Brandon Boone
  • 16,281
  • 4
  • 73
  • 100
  • There were [bugs in IE's](https://groups.google.com/forum/#!msg/comp.lang.javascript/qt_UPJW6wcg/6LwEsAOLUFsJ) 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. – RobG Oct 09 '13 at 12:11