大括号作为 ES6 函数声明语句?

Braces as an ES6 function declaration statement?

在我正在阅读的教程中找到它。 是 ES6.

我只是不确定到底发生了什么。即,用数组声明函数(?)的方式。声明为函数的冒号在哪里?

[types.ADD_TO_CART] (state, { id }) 

还有参数声明中的括号是怎么回事?

(state, { id })

这是教程。

https://medium.com/@connorleech/build-a-shopping-cart-with-vue-2-and-vuex-5d58b93c513f

[types.ADD_TO_CART] (state, { id }) {
  const record = state.added.find(p => p.id === id)
  if (!record) {
    state.added.push({
      id,
      quantity: 1
    })
  } else {
    record.quantity++
  }
}

使用 ES2015,您可以获得对象字面量的两个新特性:

// Computed object properties

const foo = 'bar'
const myObj = {
    [foo]: 'hello world'
}

// Shorthand method definitions:

const mySecondObj = {
    myMethod () {
        // code...
    }
}

示例中的代码似乎结合了两者。


此外,ES2015 为您提供了 object destructuring,它用于参数 - 因此是大括号。


Check MDN 有关新语法功能的更多详细信息。

您必须在 class 上定义一个方法而不使用 ::

class Example {
  method() {
    console.log('here')
  }
}

new Example().method()

使用 ES6 计算的 属性 名称,您可以使该方法的名称是动态的:

const name = 'method'
class Example {
  [name]() {
    console.log('here');
  }
}

new Example()[name]()

至于 ({ id }) 部分,id 表示使用解构从该动态方法的参数中提取的 属性:

// this
[types.ADD_TO_CART](state, obj) => {
   let id = obj.id;
}

// can be abbreviated to this
[types.ADD_TO_CART](state, { id }) => {

}

例如:

const name = 'method'
class Example {
  [name]({
    id
  }) {
    console.log(id);
  }
}

new Example()[name]({
  id: 'example'
})

更多资源:this one and this one and this one