命名函数与匿名函数

时间:2014-12-08 12:22:56

标签: javascript scope

有时候我会看到这样的例子,我想知道它是如何使用的。 我的意思是 this.methodA = function methodA(){} 为什么会这样?

我唯一可以想象的是,当你遇到范围问题时,不使用这个就可以使用它。 有人有想法吗?

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

}

1 个答案:

答案 0 :(得分:3)

命名函数表达式与匿名函数表达式的主要优点是它们的名称将显示在调试器(stacktraces等)中,这使得在出现错误时更容易弄清楚发生了什么。

也可以在其自己的范围内使用其名称调用命名函数。这对于创建递归函数很有用。