在查看一篇关于javascript类的文章时,作者使用了以下语法:
class GuitarAmp {
constructor ({ cabinet = 'spruce', distortion = '1', volume = '0' } = {}) {
Object.assign(this, {
cabinet, distortion, volume
});
}
}构造函数参数列表中的= {}位的用途是什么?我们不是为cabinet、distortion和volume设置默认参数吗?
发布于 2018-04-11 03:30:28
它允许您在没有任何参数的情况下调用GuitarAmp,并将提供{}的默认参数(其非结构化属性随后将被默认分配)。否则,如果函数在没有任何参数的情况下被调用,它将导致错误:
class GuitarAmp1 {
constructor ({ cabinet = 'spruce', distortion = '1', volume = '0' } = {}) {
console.log(cabinet);
}
}
class GuitarAmp2 {
constructor ({ cabinet = 'spruce', distortion = '1', volume = '0' }) {
console.log(cabinet);
}
}
new GuitarAmp1();
new GuitarAmp2();
这种默认参数解构模式可以用于任何函数,不管它是构造函数还是非构造函数。
https://stackoverflow.com/questions/49766028
复制相似问题