Export const arrow function or basic function?

2019-02-08 04:45发布

问题:

Which is better to do: export a const arrow function, like so:

export const foo = () => 'bar'

or export a regular function, like so:

export function baz() {
  return 'bar';
}

They compile like so:

exports.baz = baz;
function baz() {
  return 'bar';
}
var foo = exports.foo = function foo() {
  return 'bar';
};

It looks like using the const/arrow function combination declares an extra variable (foo), which seems to be an unnecessary extra step over the simple function declaration.

回答1:

The differences are minuscule. Both declare a variable.

  • A const variable is constant also within your module, while a function declaration theoretically could be overwritten
  • An arrow function is a function expression, not a function declaration, and the assignment can lead to problems for circular dependencies
  • An arrow function cannot be a constructor or use a dynamic this
  • An arrow function is a few characters shorter if you use a concise body and a few characters longer if you use a block body.