首页 > 解决方案 > 工厂的前后挂钩 - 范围问题

问题描述

我正在尝试构建一个简单的工厂,它将“道具”传递给注册到父级的修饰符。

但是,在下面的代码中,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);

标签: javascript

解决方案


推荐阅读