Guy
Guy

Reputation: 13286

Non anonymous vs. anonymous functions in javascript

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

Answers (2)

Brandon J. Boone
Brandon J. Boone

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.

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.

Upvotes: 1

Bergi
Bergi

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.
  • 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.

Upvotes: 2

Related Questions