如何为 Node.js 中的方法设置前后“ Hook ”?
我需要它在调用某些方法之前执行某些操作。我使用的是 node.js 10.36 和 socket.io 1.2。
最佳答案
扩展函数
:
这是对 Function.Prototype
的一点扩展
Function.prototype.before = function (callback) {
var that = this;
return (function() {
callback.apply(this, arguments);
return (that.apply(this, arguments));
});
}
Function.prototype.after = function (callback) {
var that = this;
return (function() {
var result = that.apply(this, arguments);
callback.apply(this, arguments);
return (result);
});
}
这两个扩展返回要调用的函数。
这是一个小例子:
function test(a) {
console.log('In test function ! a = ', a);
}
test(15); // "In test function ! a = 15"
与之前:
var beforeUsed = test.before(function(a) {
console.log('Before. Parameter = ', a);
});
beforeUsed(65); // "Before. Parameter = 65"
// "In test function ! a = 65"
之后:
var afterUsed = beforeUsed.after(function(a) {
console.log('After. Parameter = ', a);
});
afterUsed(17); // "Before. Parameter = 17"
// "In test function ! a = 17"
// "After. Parameter = 17"
您还可以链接:
var both = test.before(function(a) {
console.log('Before. Parameter = ', a);
}).after(function(a) {
console.log('After. Parameter = ', a);
});
both(17); // Prints as above
关于javascript - 为 Node.js 中的方法设置 before/after 钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28767271/