我不明白为什么下面代码的输入参数有{ cabinet = 'spruce', distortion = '1', volume = '0' } = {}传入。这是否意味着从该类中创建的所有新对象都包含初始化的这些参数?为什么要使用{ ... } = {}呢?
class GuitarAmp {
constructor ({ cabinet = 'spruce', distortion = '1', volume = '0' } = {}) {
Object.assign(this, {
cabinet, distortion, volume
});
}
}发布于 2018-08-23 23:47:21
构造函数期望您传入一个具有属性cabinet、distortion和volume的对象。参数是以这种方式编写的,以使所有参数都是可选的,并给出所有这些参数的默认值。
它写起来的原因如下:
constructor ({ cabinet = 'spruce', distortion = '1', volume = '0' } = {})而不是
constructor ({ cabinet = 'spruce', distortion = '1', volume = '0' })就是允许在没有任何参数的情况下调用它。第二个示例运行良好,只要您传入一个对象,但是如果您只调用new GuitarAmp(),它将失败:
TypeError:无法对属性
cabinet进行“未定义”或“null”的结构。
当没有任何东西传递给构造函数时,添加= {}使它成为一个默认的空对象来重构。
https://stackoverflow.com/questions/51994558
复制相似问题