带有Object Literals的ES6代理拦截器自引用
我有node.JS应用程序,它具有多次使用相同参数调用的方法。 (尝试组合的优化问题)
源代码非常大,我不熟悉它,我试图找到使用相同参数多次调用哪些方法,以便记住它们并提高算法的性能。
所以我试图用它们各自的参数拦截所有方法调用,将它们存储在Set()中,并查看方法调用和唯一参数之间的区别。
我正在使用ES6 Proxy对象:
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.calls和log.params.size()中查看log变量的差异,以查看记忆的最佳候选者。
这种技术效果很好,但显然不会拦截对象文字调用本身。以下是失败的示例(项目中的示例模块):
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
};
执行后,我将在我的日志变量中使用normalize函数,但不是staticFunction,因为它没有在截取的对象上调用,而是直接在适应性上调用。
截取这些方法调用的最佳方法是什么?
回答如下:您可以像这样注入您的代理:
let fitness = { … };
fitness = process.traceMethodCalls(fitness);
return fitness;
或者,只是不要使用引用原始目标的函数。相反,使用this
:
const fitness = {
staticFunction() { return true },
normalize(a, b) {
return (this.staticFunction()) ? a+b : 0;
}
};