当一个函数返回一个对象时,我们称之他为 工厂函数(factory function)。
function createJelly() {
return {
type: 'jelly',
colour: 'red'
scoops: 3
};
}
组合工厂函数
function createJelly() {
return {
type: 'jelly',
colour: 'red',
scoops: 3
};
}
function createIceCream(flavour='Vanilla') {
return {
type: 'icecream',
scoops: 3,
flavour
}
}
function createDessert() {
return {
type: 'dessert',
bowl: [
createJelly(),
createIceCream()
]
};
}
我们可以组合工厂函数来构建任意复杂的对象,这不需要我们结合使用 new 或 this
function Trifle() {
Dessert.apply(this, arguments);
}
Trifle.prototype = Dessert.prototype;
// 或者
class Trifle extends Dessert {
constructor() {
super();
}
}
// A trifle *is a* dessert 蛋糕*是*甜点
// A trifle *has* layers of jelly, custard and cream. It also *has a* topping.
// 蛋糕 *有* 果冻层,奶酪层和奶油层,顶部还 *有* 装饰配料。
function createTrifle() {
return {
type: 'trifle',
layers: [
createJelly(),
createCustard(),
createCream()
],
topping: createAlmonds()
};
}
异步的工厂函数
并非所有工厂都会立即返回数据。例如,有些必须先获取数据。
在这些情况下,我们可以返回 Promises 来定义工厂函数。