为什么输入参数有一个 "object equal another object " 传入
Why does input parameter has an "object equal another object " passed into
我很困惑为什么下面代码的输入参数传入了 { cabinet = 'spruce', distortion = '1', volume = '0' } = {}
。这是否意味着所有从 class 创建的新对象都包含这些已初始化的参数?为什么要使用 { ... } = {}
?
class GuitarAmp {
constructor ({ cabinet = 'spruce', distortion = '1', volume = '0' } = {}) {
Object.assign(this, {
cabinet, distortion, volume
});
}
}
构造函数期望您传入具有属性 cabinet
、distortion
和 volume
的单个对象。参数这样写是为了让所有的参数都是可选的,并给它们所有的默认值。
之所以这样写:
constructor ({ cabinet = 'spruce', distortion = '1', volume = '0' } = {})
而不是
constructor ({ cabinet = 'spruce', distortion = '1', volume = '0' })
就是允许它完全不带任何参数地被调用。第二个例子只要你传入一个对象就可以正常工作,但如果你只是调用 new GuitarAmp()
就会失败,它将失败:
TypeError: Cannot destructure property cabinet
of 'undefined' or 'null'.
添加 = {}
给它一个默认的空对象,当没有任何东西传递到构造函数时要解构。
我很困惑为什么下面代码的输入参数传入了 { cabinet = 'spruce', distortion = '1', volume = '0' } = {}
。这是否意味着所有从 class 创建的新对象都包含这些已初始化的参数?为什么要使用 { ... } = {}
?
class GuitarAmp {
constructor ({ cabinet = 'spruce', distortion = '1', volume = '0' } = {}) {
Object.assign(this, {
cabinet, distortion, volume
});
}
}
构造函数期望您传入具有属性 cabinet
、distortion
和 volume
的单个对象。参数这样写是为了让所有的参数都是可选的,并给它们所有的默认值。
之所以这样写:
constructor ({ cabinet = 'spruce', distortion = '1', volume = '0' } = {})
而不是
constructor ({ cabinet = 'spruce', distortion = '1', volume = '0' })
就是允许它完全不带任何参数地被调用。第二个例子只要你传入一个对象就可以正常工作,但如果你只是调用 new GuitarAmp()
就会失败,它将失败:
TypeError: Cannot destructure property
cabinet
of 'undefined' or 'null'.
添加 = {}
给它一个默认的空对象,当没有任何东西传递到构造函数时要解构。