javascript - 工厂的前后挂钩 - 范围问题
问题描述
我正在尝试构建一个简单的工厂,它将“道具”传递给注册到父级的修饰符。
但是,在下面的代码中,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);
解决方案
推荐阅读
- vb.net - 我想创建一个渐变色
- python - Python 3 - 关键错误 = 8
- reporting-services - SSRS:odbc 数据源的数据集错误
- asp.net-core - aspnet core 和 AzureAD:有没有办法拦截身份验证?
- swift - 从 App Delegate 执行 Segue - Swift
- datepicker - 从引导日期选择器中仅选择日期和月份?
- html - 父元素未使用子文本区域正确调整大小
- java - 无法卸载 JDK 10 – 内部错误 2318
- java - 在事件 JavaFX 上创建新的透明舞台
- java - Java- 运算符顺序