barry
barry

Reputation: 249

Named functions vs anonymous functions

Sometimes I see these kind of examples coming by, and I am wondering whats the use of it. I mean this.methodA = function methodA(){} why is this?

The only thing I can imagine is to use it without this when you have an issue with scoping. Anybody an idea?

function MyModule() {

  this.myMethod = function myMethod() {
    alert( 'my method' );
  };

  this.myOtherMethod = function myOtherMethod() {
    alert( 'my other method' );
  };

}
// Versus:
function MyModule() {

  this.myMethod = function () {
    alert( 'my method' );
  };

  this.myOtherMethod = function () {
    alert( 'my other method' );
  };

}

Upvotes: 4

Views: 86

Answers (1)

Quentin
Quentin

Reputation: 943564

The main advantage of named function expressions over anonymous ones is that their name will show up in debuggers (stacktraces etc) which makes it a lot easier to figure out what is going on when something goes wrong.

A named function can also be called using its name from within its own scope. This is useful for creating recursive functions.

Upvotes: 3

Related Questions