【问题标题】:Large list of parameters in javascript constructorsjavascript 构造函数中的大量参数列表
【发布时间】:2016-10-29 13:37:06
【问题描述】:

我在 cmets 的教练告诉我这里有很多参数,他是什么意思?

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;
    }

【问题讨论】:

  • 这是我挑战的一部分,但我不知道该怎么做

标签: javascript oop inheritance


【解决方案1】:

您的idnamecostquantityshortDescriptionfullDescription参数(您会经常听到它们被称为“参数”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 参数”而不区分参数/参数是绝对可以的。但这就是区别:声明中的抽象事物与调用中的具体事物。

【讨论】:

    猜你喜欢
    • 2019-09-04
    • 2016-08-06
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 2015-08-02
    • 2020-07-13
    • 1970-01-01
    相关资源
    最近更新 更多