在构造函数JavaScript中指定默认值
有没有办法在构造函数中定义对象比例的默认值?我有一个接受多个参数的构造函数,如果没有给出参数,我希望有一些默认值。目前,我有以下方法:在构造函数JavaScript中指定默认值,javascript,class,constructor,Javascript,Class,Constructor,有没有办法在构造函数中定义对象比例的默认值?我有一个接受多个参数的构造函数,如果没有给出参数,我希望有一些默认值。目前,我有以下方法: class Item{ constructor(id, name, um, unitPrice, quantity, discounts, taxes){ this.id = id || -1, this.name = name || 'n/a', this.um = um || new UnitOfMeasurment
class Item{
constructor(id, name, um, unitPrice, quantity, discounts, taxes){
this.id = id || -1,
this.name = name || 'n/a',
this.um = um || new UnitOfMeasurment(),
this.unitPrice = unitPrice || 0,
this.quantity = quantity || 0,
this.discounts = discounts || [],
this.taxes = taxes || []
}
}
function UnitOfMeasurment(id, name) {
this.id = id || -1;
this.name = name || 'n/a';
}
看起来还可以,但是如果我创建了一个只包含最后3个参数的新项目,那么所有参数都将被分配错误。这应该可以解决问题。它们被称为默认参数
class Item{
constructor(id, name, um, unitPrice, quantity = 0, discounts = [], taxes = []){
this.id = id || -1,
this.name = name || 'n/a',
this.um = um || new UnitOfMeasurment(),
this.unitPrice = unitPrice || 0,
this.quantity = quantity,
this.discounts = discounts,
this.taxes = taxes
}
}
您应该给出一个对象,这样可以避免不需要的参数
。。。
建造师({
id=-1,
名称='不适用',
um=新的测量单位(),
单价=0,
量
折扣,
税
})
...
新项目({
名称
税
});
举例说明如何仅分配最后三个参数您不能只传递三个参数,而期望函数知道这些参数应分配给最后三个参数。对于任何其他参数,您必须传递未定义的。但是,有这么多参数,可能最好传递一个配置对象。我不认为这是他的意思,如果你添加…={}
在对象模式之后,也可以不带参数地调用构造函数。