您的id、name、cost、quantity、shortDescription 和 fullDescription 是参数(您会经常听到它们被称为“参数”1) 到Product 函数。他说六个太多了。这是风格和维护的问题,意见可能会有所不同,但这就是他的意思。
您可以考虑改用单个 options 参数:
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 及更高版本中,您可以使用 destructuring 参数来做到这一点:
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 及更高版本。
1parameters vs. arguments:在声明中,技术上正确的术语是“参数”。在 call 中,术语是“参数”。例如,这是一个采用name 参数的函数:
function foo(name) {
// ...
}
...这里我们用参数“Douglas”来称呼它:
foo("Douglas");
在日常讲话中,谈论“name 参数”而不区分参数/参数是绝对可以的。但这就是区别:声明中的抽象事物与调用中的具体事物。