是否可以使用多个构造函数来创建1个新实例?

时间:2018-03-30 22:54:13

标签: javascript constructor

是否有一种直接的方法可以使用2个或更多constructor个函数来创建1个新实例?

例如,

function Vehicle(manufacturer, cost) {
    this.manufacturer = manufacturer;
    this.cost = cost;
}

function Aircraft(crewSize, range) {
    this.crewSize = crewSize;
    this.range = range;
}

let p51Mustang = new Vehicle + Aircraft ???

我知道可以使用call()将构造函数链接在一起,就像这样,

function Vehicle(manufacturer, cost) {
    this.manufacturer = manufacturer;
    this.cost = cost;
}

function Aircraft(manufacturer, cost, crewSize, range) {
    Vehicle.call(this, manufacturer, cost)
    this.crewSize = crewSize;
    this.range = range;
}

let p51Mustang = new Aircraft('North American', '$50,000', 1, '2,656 Km'); 

但有没有办法通过同时调用两个构造函数而不是将它们链接在一起来完成此操作?非常感谢任何输入!

2 个答案:

答案 0 :(得分:1)

您可以使用Object#assign

这是一个片段:

function Vehicle(manufacturer, cost) {
    this.manufacturer = manufacturer;
    this.cost = cost;
}

function Aircraft(crewSize, range) {
    this.crewSize = crewSize;
    this.range = range;
}


let p51Mustang = Object.assign( new Vehicle('BMW', 1000), new Aircraft(10, 200))

console.log(obj)

答案 1 :(得分:1)

您可以使用Object.assign



function Vehicle(manufacturer, cost) {
  return {
    manufacturer,
    cost
  }

}

function Aircraft(crewSize, range) {
  return {
    crewSize,
    range
  }
}

let p51Mustang = Object.assign(Vehicle("North American", '$50,000'), Aircraft(1, '2,656 Km'));
console.log(p51Mustang);