我正在尝试使用普通函数或箭头函数导出.js文件中的函数。但我不明白推荐哪一个。
导出正常功能
module.exports = function(id) {
console.log(id);
};
导出箭头函数
const test = id => {
console.log(id);
}
module.exports = test;
下面是我心中的几个问题。
1.如果普通函数比箭头函数更受推荐,那么为什么我不推荐使用箭头函数。
1.如果箭头功能比正常功能更受推荐,那么为什么我不被推荐使用正常功能。
如何理解推荐的方法,尤其是在导出函数的场景中?
2条答案
按热度按时间fnvucqvd1#
These two snippets aren't identical. First snippet results in anonymous function, while second snippet results in named function,
require('...').name === 'test'
(this may be useful for debugging).A more suitable comparison is
vs
There's no difference between these arrow and regular function in such case because they don't use features that are specific to them (e.g.
this
context).Anonymous arrow function takes less characters to type but this benefit disappears when there's a need to give a function a name via temporary
test
variable. They also may result in lesser memory footprint, though this concern can be ignored because the difference is negligible.Also, named arrow functions can result in more verbose output than regular functions definitions if they are transpiled to ES5:
is transpiled to
While it could be:
This isn't a concern for Node.js or other ES6 environment.
TL;DR: if a function needs to have a name for debugging or other purposes, it makes sense to use:
If a function doesn't need a name, it's:
This is true for functions that don't use features specific to these function types.
t8e9dugd2#
或