首页 > 解决方案 > In Javascript, what do you call this "identity function" - () => ({obj})

问题描述

I've seen this type of JavaScript code (contrived):

 const a = "hello"
 const b = () => ({a})

Is this just shorthand for this equivalent fat arrow function:

const b = () => { return {a} }

Or does it have some other purpose? And what do you call these?

It seems a lot to add a construct just to save one reserved word.

标签: javascriptfunctionsyntax

解决方案


我想您是在询问箭头函数的右侧。

它更简洁,具有特殊规则,如果右侧是要返回的单个表达式,则不必是{ return expr },而只是expr

const sq = (x => x * x);
const hyphenAround = (s => `-${s}-`);
[1, 3, 5].map(a => a * a)
[1, 3, 5].reduce((a, b) => a + b)

const sq = (x => x * x);
const hyphenAround = (s => `-${s}-`);

console.log(sq(3));
console.log(hyphenAround("hello"));
console.log([1, 3, 5].map(a => a * a));
console.log([1, 3, 5].reduce((a, b) => a + b));

在您的示例中,它是

const a = "hello"
const b = () => ({a})

这与

const a = "hello"
const b = () => ({a: a})

这些被称为速记属性名称

let a = "hello"
const b = () => ({
  a
});

console.log(b());

a = "a long sentence";
console.log(b());

x = 123;
y = "hello"
z = [1, 3, 5];

console.log({
  x,
  y,
  z
});


推荐阅读