NodeJS js:导出普通函数还是箭头函数?

tjjdgumg  于 2022-12-03  发布在  Node.js
关注(0)|答案(2)|浏览(139)

我正在尝试使用普通函数或箭头函数导出.js文件中的函数。但我不明白推荐哪一个。
导出正常功能

module.exports = function(id) {
   console.log(id);
};

导出箭头函数

const test = id => {
  console.log(id);
}
module.exports = test;

下面是我心中的几个问题。
1.如果普通函数比箭头函数更受推荐,那么为什么我不推荐使用箭头函数。
1.如果箭头功能比正常功能更受推荐,那么为什么我不被推荐使用正常功能。
如何理解推荐的方法,尤其是在导出函数的场景中?

fnvucqvd

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

module.exports = function test(id) {
   console.log(id);
};

vs

const test = id => {
  console.log(id);
}
module.exports = test;

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:

const test = () => {}

is transpiled to

var test = function test() {}

While it could be:

function test() {}

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:

module.exports = function test(id) {
   console.log(id);
};

If a function doesn't need a name, it's:

module.exports = id => {
  console.log(id);
};

This is true for functions that don't use features specific to these function types.

t8e9dugd

t8e9dugd2#

const App = () => console.log("This is an app.");
export default App;

export const App = () => console.log("This is an app.");

相关问题