javascript - 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.
解决方案
我想您是在询问箭头函数的右侧。
它更简洁,具有特殊规则,如果右侧是要返回的单个表达式,则不必是{ 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
});
推荐阅读
- java - 有没有 java.util.Optional.or(Supplier
) JDK 8 的实现 - javascript - 跨动态加载元素的连续动画
- autodesk-forge - 在查看器中加载 BIM 文件时出现问题
- visual-c++ - 内联静态变量在 Visual C++ 中的模块之间是唯一的吗?
- javascript - 为什么我必须重新加载页面才能让我的 JS 事件起作用?
- .net-core - 在 azure 函数的代码中获取 ServiceLocator
- installation - yum install 以“已经安装和最新版本”结尾,而“pip -V”显示“没有这样的文件或目录”
- android - OnBindViewHolder on update autoScroll to top
- reactjs - 订阅 i18n 到 mobx,基于 observable react 进行翻译
- android - 使用 React Native Hooks