使用单个factory function填充实例非常简单。在下面的示例中,我使用工厂函数aircraftFactory()
创建一个名为supermarine
的新实例。但是我不确定如何构造它,以便aircraftFactory()
和engines()
可以一起使用来创建supermarine
。
"use strict"
function aircraftFactory(x) {
return {
manufacturer: x.manufacturer,
factory: x.factory
}
}
function engines(x) {
return {
numberOfEngines: x.numberOfEngines,
costPerEngine: x.costPerEngine
}
}
let supermarine = aircraftFactory({manufacturer: 'Supermarine', factory: 'Southampton'});
document.querySelector('.output').textContent = supermarine.manufacturer;
<div class='output'></div>
我试图像这样将它们链接在一起,但这引发了错误。
未被捕获的TypeError:aircraftFactory(...)。engines不是函数
let supermarine = aircraftFactory({manufacturer: 'Supermarine', factory: 'Southampton'}).engines({numberOfEngines: 1, costPerEngine: 35000});
我知道必须有一个模式,但是我找不到示例或弄清楚它。谢谢你的帮助!
最佳答案
要将engines
扩展到aircraftFactory
,您需要使用prototype
原型扩展/继承了您的属性和方法。
尝试这个
"use strict"
function aircraftFactory(x) {
this.manufacturer = x.manufacturer;
this.factory = x.factory;
}
function engines(x) {
return {
numberOfEngines: x.numberOfEngines,
costPerEngine: x.costPerEngine
}
}
//This is where you extend engines
aircraftFactory.prototype.engines = engines;
//Create the instance of aircraftFactory
let supermarine = new aircraftFactory({manufacturer: 'Supermarine', factory: 'Southampton'}).engines({numberOfEngines: 1, costPerEngine: 35000});
关于javascript - 是否可以使用2个工厂函数来填充1个实例?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50072218/