ES6中函数的数组样式解构是做什么的? [英] What does this array-style destructuring on a function do in ES6?
问题描述
我通读了 redux-actions
教程,他们使用(我认为是)解构而感到困惑。下面是一个示例(增量
& 减量
都是 createAction返回的函数
功能)。
I read through the redux-actions
tutorial, and am confused by their use of (what I believe to be) destructuring. Below is an example (increment
& decrement
are both functions returned by the createAction
function).
const { createAction, handleActions } = window.ReduxActions;
const reducer = handleActions(
{
[increment]: state => ({ ...state, counter: state.counter + 1 }),
[decrement]: state => ({ ...state, counter: state.counter - 1 })
},
defaultState
);
这是另一个使用的例子:
Here's another example of this being used:
const { createActions, handleActions, combineActions } = window.ReduxActions;
const reducer = handleActions(
{
[combineActions(increment, decrement)]: (
state,
{ payload: { amount } }
) => {
return { ...state, counter: state.counter + amount };
}
},
defaultState
);
有人可以解释这些行中发生了什么吗?简单来说,我只看到 {[function] :()=> ({})}
,并且不明白这是做什么的。
Can somebody explain what's happening in those lines? In simplified terms, I just see {[function]: () => ({})}
, and don't understand what this does.
推荐答案
这确实是计算属性名称,但有一个扭曲 - 一个函数用作键,而不是字符串。
That's indeed a computed property name, but with a twist - a function is used as a key, not a string.
在您记住每个函数可以安全地转换为字符串之前,它可能看起来很混乱 - 结果就是该函数的源代码。这正是这里发生的事情:
It might look confusing until you remember that each function can be safely cast to string - the result is that function's source code. And that's exactly what happens here:
function x() {}
const obj = { [x]: 42 };
console.log( obj[x] ); // 42
console.log( obj[x.toString()] ); // 42, key is the same actually
console.log( Object.keys(obj) ); // ["function x() {}"]
这种方法的优点是你不喜欢不需要创建额外的键 - 如果你有一个功能参考,你已经有一个。事实上,你甚至不需要引用 - 它足以拥有一个具有相同源的函数:
The advantage of such approach is that you don't need to create additional keys - if you have a function reference, you already have one. In fact, you don't even have to have a reference - it's enough to have a function with the same source:
const one = () => '';
const two = () => '';
console.log(one === two); // false apparently
const fatArrObj = { [one]: 42 }
fatArrObj[two]; // 42, take that Oxford scholars!!
缺点是函数在每次被用作键时被强制转换为字符串 - a(据称是次要的)性能命中。
The disadvantage is that function is cast to string each time it's used as key - a (supposedly minor) performance hit.
为了增加一些乐趣,这是有效的对象文字:
To add some fun, this is valid object literal:
{
[null]: null, // access either with [null] or ['null']
[undefined]: undefined,
[{ toString: () => 42 }]: 42 // access with, you guess it, 42 (or '42')
}
...这个可能会进入奇怪的面试问题:
... and this one might go into book of weird interview questions:
const increment = (() => { let x = 0; return () => ++x })();
const movingTarget = { toString: increment };
const weirdObjectLiteral = { [movingTarget]: 42 };
console.log( weirdObjectLiteral[movingTarget] ); // undefined
这篇关于ES6中函数的数组样式解构是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!