javascript对象如何只有没有预定义键的属性

时间:2017-01-19 10:54:28

标签: javascript ecmascript-6

我有一些“愚蠢”的问题,抱歉,但我真的不明白它是如何运作的。

在这个createReducer调用中,我们传递了第二个参数 - js object(据我所知)。

但我没有看到任何关键......唯一的功能。它是如何工作的?

  export const todos = createReducer([], {
      [ActionTypes.ADD_TODO](state, action) {
        let text = action.text.trim()
        return [ ...state, text ]
      }
    })


function createReducer(initialState, handlers) {
  return function reducer(state = initialState, action) {
    if (handlers.hasOwnProperty(action.type)) {
      return handlers[action.type](state, action)
    } else {
      return state
    }
  }
}

我希望看到一些像:

    {
          [ActionTypes.ADD_TODO] : (state, action) => {
                let text = action.text.trim()
                return [ ...state, text ]
              }
        }

与这种结构相同:它是一个关键的功能?它怎么样?

const dynamicRoutes = {
    component : AppComponent,
    childRoutes : [
        {
            path : "/",
            getComponent(location, cb) {
                System.import("../modules/landing-page/LandingPage.module")
                    .then(loadRoute(cb))
                    .catch(errorLoading);
            }
        }

    ]
};

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

它是方法的简写符号。关键是函数的名称。因此[ActionTypes.ADD_TODO](state, action) {相当于[ActionTypes.ADD_TODO]: function(state, action) {

答案 1 :(得分:2)

这些是有效的object initializer语法。 第二个示例是MethodDefinitionlink to spec

的简单情况

案例[ActionTypes.ADD_TODO](state, action)也是MethodDefinition,但方法/属性名称定义为ComputedPropertyName,其语法为[ AssignmentExpression[In, ?Yield] ]。 在ComputedPropertyNames的情况下,可以在方括号之间放置变量/对象属性,并且该值将在新创建的对象中用作属性名称。