ECMAScript6-对象的扩展

59 阅读1分钟

扩展操作符

应用

传递多个参数

function getMinValue() {
  return Math.min(...aarguments)
}
getMinValue(10, 20, -88, 34, -117, -200)

合并对象

let smallDog = {name1:'滚滚', age1:2}
let bigDog = {name2:'蛋蛋', age2:10}
let animals = {...smallDog, ...bigDog}

属性的简写

  1. 如果 key 和变量名字一致,可以省略括号指定一次即可
  2. 如果 value 是一个函数,可以将 function 去掉
const msg = 'hello es6'
const name = 'lxx'
const obj = {
  msg,
  name,
  run() {
    console.log('running')
  }
}

属性的赋值器(setter)和取值器(getter)实际上也采用这种写法。

const cart = {
  _wheels:4,
  get wheels(){
    return this._wheels
  },
  set wheels(value){
    if(value < this._wheels){
      throw new Error('数值太小了')
    }
    this._wheels = value
  }
}