簡體   English   中英

在ES6中,對函數的這種數組樣式的結構分解有什么作用?

[英]What does this array-style destructuring on a function do in ES6?

我通讀了redux-actions教程 ,並對其使用(我相信是)解構感到困惑。 下面是一個示例( incrementdecrement都是createAction函數返回的兩個函數)。

const { createAction, handleActions } = window.ReduxActions;

const reducer = handleActions(
  {
    [increment]: state => ({ ...state, counter: state.counter + 1 }),
    [decrement]: state => ({ ...state, counter: state.counter - 1 })
  },
  defaultState
);

這是使用此方法的另一個示例:

const { createActions, handleActions, combineActions } = window.ReduxActions;
​
const reducer = handleActions(
  {
    [combineActions(increment, decrement)]: (
      state,
      { payload: { amount } }
    ) => {
      return { ...state, counter: state.counter + amount };
    }
  },
  defaultState
);

有人可以解釋在這些方面發生了什么嗎? 簡而言之,我只看到{[function]: () => ({})} ,卻不了解它的作用。

那確實是一個經過計算的屬性名稱 ,但是有點兒曲折-函數用作鍵,而不是字符串。

在您記住可以將每個函數安全地轉換為字符串之前,它可能看起來很混亂-結果就是該函數的源代碼。 這就是這里發生的情況:

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() {}"]

這種方法的優點是您不需要創建其他鍵-如果您具有功能引用,那么您已經擁有一個。 實際上,您甚至不需要引用-具有相同源的函數就足夠了:

const one = () => '';
const two = () => '';
console.log(one === two); // false apparently 
const fatArrObj = { [one]: 42 } 
fatArrObj[two]; // 42, take that Oxford scholars!!

缺點是函數每次用作鍵時都會強制轉換為字符串,這會導致性能下降。


為了增加樂趣,這是有效的對象文字:

{ 
   [null]: null, // access either with [null] or ['null']
   [undefined]: undefined, 
   [{ toString: () => 42 }]: 42 // access with, you guess it, 42 (or '42')
}

...而這可能會涉及到奇怪的訪談問題:

const increment = (() => { let x = 0; return () => ++x })();
const movingTarget = { toString: increment };
const weirdObjectLiteral = { [movingTarget]: 42 };
console.log( weirdObjectLiteral[movingTarget] ); // undefined

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM