javascript构造函数中的大量参数列表

javascript构造函数中的大量参数列表,javascript,oop,inheritance,Javascript,Oop,Inheritance,我的教练在评论中告诉我,这里有一大堆参数,他是什么意思 function Product(id, name, cost, quantity, shortDescription, fullDescription) { this.id = id; this.name = name; this.cost = cost; this.quantity = quantity; this.shortDescription = shortDescrip

我的教练在评论中告诉我,这里有一大堆参数,他是什么意思

function Product(id, name, cost, quantity, shortDescription, fullDescription) {
      this.id = id;
      this.name = name;
      this.cost = cost;
      this.quantity = quantity;
      this.shortDescription = shortDescription;
      this.fullDescription = fullDescription;
    }

您的
id
name
cost
quantity
shortDescription
fullDescription
都是
产品
功能的参数(您经常会听到它们被称为“参数”1)。他说六个太多了。这是一个风格和维护的问题,观点可能会有所不同,但这就是他所说的

您可以考虑使用单一的<>代码>选项>代码>参数:

function Product(options) {
    this.id = options.id;
    this.name = options.name;
    this.cost = options.cost;
    this.quantity = options.quantity;
    this.shortDescription = options.shortDescription;
    this.fullDescription = options.fullDescription;
}
…您可以通过传入一个具有这些属性的对象来调用它,如下所示:

var p = new Person({
    id: 42,
    name: "Douglas Adams",
    cost: "Priceless",
    quantity: 0,
    shortDescription: "Great author",
    fullDescription: "Mostly harmless"
});
在ES2015及更高版本中,您可以使用分解参数来实现这一点:

function Product({id, name, cost, quantity, shortDescription, fullDescription}) {
    // Note -----^-----------------------------------------------------------^
    this.id = id;
    this.name = name;
    this.cost = cost;
    this.quantity = quantity;
    this.shortDescription = shortDescription;
    this.fullDescription = fullDescription;
}
您仍然以相同的方式调用它,使用对象:

let p = new Person({
    id: 42,
    name: "Douglas Adams",
    cost: "Priceless",
    quantity: 0,
    shortDescription: "Great author",
    fullDescription: "Mostly harmless"
});
再次重申:这是ES2015及以上


1参数与参数:在声明中,技术上正确的术语是“参数”。在调用中,术语是“参数”。例如,这里有一个函数使用
名称
参数:

…这里我们用“道格拉斯”这个论点来称呼它:


在日常用语中,谈论“name参数”而不区分参数/参数是绝对正确的。但这就是区别:声明中的抽象内容与调用中的具体内容。

这是我挑战的一部分,但我不知道该怎么办
function foo(name) {
    // ...
}
foo("Douglas");