我正在尝试建立一个简单的工厂,该工厂将“ props”传递给注册到父级的修饰符。
但是,在下面的代码中,props
对象在调用posthooks()
时尚未定义。
const factory = function({ collection = [], modifiers = [] }) {
let props = { collection, timesRan: 0 };
const registerRun = () => {
props.timesRan = props.timesRan + 1;
}
const prehooks = function() {
modifiers.forEach((modifier) => {
modifier.prehook(props);
registerRun();
});
};
const posthooks = function(props) {
modifiers.forEach((modifier) => {
modifier.posthook(props);
registerRun();
});
};
prehooks();
posthooks();
return props;
};
// test case
const collection = [
{
"name": "Jimmy",
"id": 1
},
{
"name": "Johnny",
"id": 2
},
]
// modifier
const modifier = {
prehook: (props) => {
if (props && props.collection) {
console.log('pre hook ran');
props.collection = props.collection.map(item => Object.assign({}, { points: 100 }, item));
}
return props;
},
posthook: (props) => {
if (props && props.collection) {
console.log('post hook ran');
props.collection = props.collection.map(item => Object.assign({}, { id: String(item.id) }, item));
}
return props;
}
}
// test the factory
const modifiers = [ modifier ];
const returnValue = factory({ collection, modifiers } );
console.log('returnValue', returnValue);