javascript - 为 Node.js 中的方法设置 before/after 钩子(Hook)

标签 javascript node.js

如何为 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/

相关文章:

javascript - 在 req.body 中接收两个对象

node.js - 在 Apache Cassandra 中添加列

node.js - Grunt 缩小了 JS 和 CSS 文件,其版本位于浏览器缓存中

node.js - mongoose Schema 数组,里面有 2 个混合对象

node.js - 在 Heroku Node.js 应用程序上上传图像时出错

javascript - 您可以创建一个属性并动态填充值吗?

javascript - GWT 如何在不点击按钮的情况下每 5 分钟自动刷新页面?

javascript - 在 HTML 中存储任意数据

javascript - Highcharts 列工具提示 - 始终位于顶部 + 适合容器

javascript - 如何配置使用 createServer 创建的服务器以在已创建时填充 cors?