简体   繁体   中英

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' );
  };

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM