使用单个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(...)。引擎不是函数
let supermarine = aircraftFactory({manufacturer: 'Supermarine', factory: 'Southampton'}).engines({numberOfEngines: 1, costPerEngine: 35000});
我知道必须有一个模式,但我找不到一个例子或想出来。谢谢你的帮助!
答案 0 :(得分:2)
我想我有一个建议:
function engines(x) {
return {
numberOfEngines: x.numberOfEngines,
costPerEngine: x.costPerEngine
}
}
如果您通过引擎:
function aircraftFactory(x, engine) {
let aircraft = {
manufacturer: x.manufacturer,
factory: x.factory
};
if (engine) {
aircraft.numberOfEngines = engine.numberOfEngines;
aircraft.costPerEngine = engine.costPerEngine;
}
return aircraft;
}
你可以创建一个这样的实例:
let aircraft = aicraftFactory(x, engineFactory(y));
但是如果你想在不知道名字的情况下创建属性:
function aircraftFactory(x, extended) {
let aircraft = {
manufacturer: x.manufacturer,
factory: x.factory
};
if (engine) {
for (let key in extended) {
aircraft[key] = extended[key];
}
}
return aircraft;
}
答案 1 :(得分:1)
要将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});