这是什么语法:{variable1,variable2,variable3}?

时间:2017-03-15 08:14:49

标签: javascript ecmascript-6

我看到了以下ES6代码并且感到困惑:

class GuitarAmp {
  constructor ({ cabinet = 'spruce', distortion = '1', volume = '0' } = {}) {
    Object.assign(this, {
      cabinet, distortion, volume
    });
  }
}

Object.assign的第二个参数是什么?它不是一个对象,它是什么?我只是注意到它也是构造函数参数的一部分,这部分:

{ cabinet = 'spruce', distortion = '1', volume = '0' } = {}

我不熟悉这种新语法,所以我不知道如何查找它,因为我不知道它叫什么。有人知道这个词吗?

3 个答案:

答案 0 :(得分:3)

所以,在上面的代码中,我相信:

{
  cabinet, distortion, volume
}

在ES5中:

{
   cabinet: cabinet,
   distortion: distortion,
   volume: volume,
}

键和值相同时,它只是写对象的简短形式。

答案 1 :(得分:1)

第一个参数的默认值为{},但如果提供,我们在第一个参数对象中嵌套了默认值,如cabinet = 'spruce', distortion = '1', volume = '0'

因此,如果第一个对象参数提供有例如{ cabinet = 'test', distortion = '4', volume = '2' }然后,this将如下

{ 
  cabinet: 'test', 
  distortion: '4', 
  volume: '2' 
}

否则,它将具有param中提供的默认值。

答案 2 :(得分:1)

它是使用简写语法的对象文字。这只是语法糖。

var a = "A";
var b = "B";
var c = "C";

这两个是相同的:

{ a: a, b: b, c: c }
{ a, b, c }

换句话说,如果将变量抛出到对象文字中,那么属性名称将变为变量名称。

相关问题