es6哈希数组索引函数调用混合语法

egu*_*eys 8 javascript ecmascript-6 redux

这是什么样的ES6语法?

{
  [ActionTypes.Repo](state, { username, res }) {
    /* ... */
  },

  [ActionTypes.Repo2](state, { username, res }) {
    /* ... */
}
Run Code Online (Sandbox Code Playgroud)

取自:https://github.com/quangbuule/redux-example/blob/master/src/js/reducers/Repo.js

Fel*_*ing 24

这些是方法定义,计算属性名称和工作中的解构.

方法定义提供了一种创建包含函数的属性的简明方法:

// before
var obj = {
  foo: function() {}
};

// now
var obj = {
   foo() {}
};
Run Code Online (Sandbox Code Playgroud)

这与在class定义中创建方法的语法相同.

计算属性允许您将任何表达式的结果用作对象文字中的属性名称:

var foo='somePropertyName';

// before
var obj = {};
obj[foo] = 42;

// now

var obj = {
  [foo]: 42
};
Run Code Online (Sandbox Code Playgroud)

当然,这也适用于方法定义:

var obj = {
  [foo]() {}
};
Run Code Online (Sandbox Code Playgroud)

解构就像模式匹配,如果你需要的话,它更容易引用数组/对象的嵌套属性:

// before
function foo(obj) {
  var username = obj.username;
  var res = obj.res;
}

// now
function foo({username, res}) {

}
Run Code Online (Sandbox Code Playgroud)