带有对象文字自引用的 ES6 代理拦截器

ES6 Proxy interceptor with Object Literals self-references

我有 node.JS 个应用程序,其中的方法使用相同的参数多次调用。 (尝试组合的优化问题)

源代码很大,我不熟悉,我正在尝试查找使用相同参数多次调用哪些方法,以便记住它们并提高算法的性能。

所以我试图拦截所有方法调用及其各自的参数,将它们存储在 Set() 中并查看方法调用和唯一参数之间的区别。

我像这样使用 ES6 代理对象:

process.log = {};
process.traceMethodCalls = function (obj) {
    return new Proxy(obj, {
        get(target, method, receiver) {
            if (typeof process.log[method] === 'undefined') {
                process.log[method] = { calls: 0, params: new Set() };
            }
            return function (...args) {
                process.log[method].calls += 1;
                process.log[method].params.add(JSON.stringify(args));
                return target[method].apply(this, args);
            };
        }
    });
}

然后我可以查看 log 变量以了解 log.calls[=48= 的差异]()查看最佳记忆候选。

这种技术效果很好,但显然不会拦截对自身的对象字面量调用。 这是失败的示例 (项目中的示例模块)

module.exports = function (app) {
    const fitness = {
        staticFunction: () => true,
        normalize: (a, b) => {
            return (fitness.staticFunction()) ? a+b : 0;
        }
    };
    return process.traceMethodCalls(fitness); // injected my proxy here
};

执行后,我的 log 变量中会有 normalize 函数,但没有 staticFunction 因为它不是在截获的对象上调用的,而是直接在 fitness 上调用的。

拦截这些方法调用的最佳方法是什么?

您可以像这样注入您的代理:

let fitness = { … };
fitness = process.traceMethodCalls(fitness);
return fitness;

或者,不要使用引用原始目标的函数。相反,使用 this:

const fitness = {
    staticFunction() { return true },
    normalize(a, b) {
        return (this.staticFunction()) ? a+b : 0;
    }
};