[英]What is the purpose using a named function when assigning to a variable in JavaScript?
I recently came across this pattern in the source for https://github.com/yeoman/generator-webapp : 我最近在https://github.com/yeoman/generator-webapp的源代码中遇到了这种模式:
AppGenerator.prototype.packageJSON = function packageJSON() {
this.template('_package.json', 'package.json');
};
What's the purpose of giving the function the name "packageJSON" when you're going to assign it to a variable or object property anyways? 当你要将函数分配给变量或对象属性时,为函数命名为“packageJSON”的目的是什么? I've always used anonymous functions in similar cases.
在类似的情况下,我总是使用匿名函数。
For debugging purposes. 用于调试目的。 If you use a named function you can see that name in the call stack trace in your favorite dev tools.
如果使用命名函数,则可以在最喜欢的开发工具中的调用堆栈跟踪中看到该名称。 Otherwise you'd see
anonymous function
. 否则你会看到
anonymous function
。
That's called a named function expression (or NFE) and it makes the debugging process much easier. 这称为命名函数表达式 (或NFE),它使调试过程更容易。
An important detail to remember is that this name is only available in the scope of a newly-defined function;
需要记住的一个重要细节是,此名称仅在新定义的函数范围内可用; specs mandate that an identifier should not be available to an enclosing scope:
规范要求标识符不适用于封闭范围:
var f = function foo(){
return typeof foo; // "foo" is available in this inner scope
};
// `foo` is never visible "outside"
typeof foo; // "undefined"
f(); // "function"
As others says, for debugging purposes mainly. 正如其他人所说,主要用于调试目的。 But not only that.
但不仅如此。 For instance, you can rely on the fact that in function's body, you can access to the function itself using the name you set.
例如,您可以依赖以下事实:在函数体中,您可以使用您设置的名称访问函数本身。 To give a silly example:
举个愚蠢的例子:
var sum = function (a, b) {
if (a < 3)
return sum(3 + a, b);
return a + b;
}
sum(1, 2) // 3;
But let's see what happens now: 但是让我们看看现在发生了什么:
var aSum = sum;
sum = null;
aSum(1, 3); // TypeError: sum is not a function
Naming the function, will cover that use case: 命名函数,将涵盖该用例:
var sum = function sum(a, b) {
if (a < 3)
return sum(3 + a, b);
return a + b;
}
sum(1, 2) // 6
var aSum = sum;
sum = null;
aSum(1, 2) // 6
That's because in the body of the function, the name of the function is always referring to it, and is not taken from another scope, like the first example. 那是因为在函数体中,函数的名称总是引用它,而不是像第一个例子那样从另一个范围中获取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.