1 什么是Factory Functions?
当一个函数,返回值为对象,称之为‘工厂函数’
2 Parameterized Factory Functions(带参数的工厂函数)
function createIceCream(flavour='Vanilla') {
return {
type: 'icecream',
scoops: 3,
flavour
}
}
3 Composable Factory Functions(功能组合的工厂函数)
function createTrifle() {
return {
type: 'trifle',
layers: [
createJelly(),
createCustard(),
createCream()
],
topping: createAlmonds()
};
}
4 Async Factory Functions(异步工厂函数)
function getMeal(menuUrl) {
return fetch(menuUrl)
.then(result => result.json())
.then(json => createMeal(json));
}
function createMeal(courses=[]) {
return {
type: 'meal',
courses
};
}
5 函数和方法
function createJelly() {
return {
type: 'jelly',
colour: 'red'
scoops: 3
};
}
function eat(jelly) {
if(jelly.scoops > 0) {
return { ...jelly, scoops: jelly.scoops - 1 };
} else {
return jelly;
}
}
createJelly().eat();
参考文献:https://www.sitepoint.com/factory-functions-javascript/?utm_source=javascriptweekly&utm_medium=email