【问题标题】:es6 hash array index function call mixed syntaxes6哈希数组索引函数调用混合语法
【发布时间】:2015-07-13 11:44:25
【问题描述】:

这是什么 ES6 语法?

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

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

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

【问题讨论】:

    标签: javascript ecmascript-6 redux


    【解决方案1】:

    他们是工作中的method definitionscomputed property namesdestructuring

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

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

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

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

    var foo='somePropertyName';
    
    // before
    var obj = {};
    obj[foo] = 42;
    
    // now
    
    var obj = {
      [foo]: 42
    };
    

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

    var obj = {
      [foo]() {}
    };
    

    解构类似于模式匹配,如果您只需要这样,就可以更轻松地引用数组/对象的嵌套属性:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-15
      • 2021-11-05
      • 2019-03-22
      • 2013-07-20
      • 1970-01-01
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多