Javascript node.js中函数的挂钩
如何在函数上应用钩子。我想在函数上应用前后钩子,以便在调用该函数时触发这些钩子。我见过express.js的中间件概念,但它只适用于路由,不适用于函数,因为它用于路由处理。我需要为我的函数使用相同类型的钩子,所以无论何时在钩子前后在服务器端调用我的函数,钩子都会触发Javascript node.js中函数的挂钩,javascript,node.js,Javascript,Node.js,如何在函数上应用钩子。我想在函数上应用前后钩子,以便在调用该函数时触发这些钩子。我见过express.js的中间件概念,但它只适用于路由,不适用于函数,因为它用于路由处理。我需要为我的函数使用相同类型的钩子,所以无论何时在钩子前后在服务器端调用我的函数,钩子都会触发 function main(){ console.log("When ever this function is called as myfun()"); } function after(){ console.log(
function main(){ console.log("When ever this function is called as myfun()"); }
function after(){
console.log("called afer when ever manin is called");
}
您可以使用一种函数组合/链接模式: 例如:
function chain() {
const fns = Array.prototype.slice.call(arguments);
return function (result) {
return fns.reduce((result, fn) => fn.call(this, result), result);
};
};
chained = chain(before, main, after);
chained();
你能举个例子吗。为什么不简单地包装函数?@davintroon Eidt举个例子