JS函数执行监控:如何适配Math及原型方法的计数需求?
函数执行次数监控:适配全局、对象与原型方法
问题背景
我正在开发一款面向学生的前端工具库(个人项目),整体逻辑参考Jest框架,核心功能是读取JS文件中的变量与代码并执行测试,输出可视化面板。当前需要实现监控任意函数执行次数并获取计数的功能,但最初的实现仅支持Number()、parseInt()这类挂载在window上的全局方法,无法适配Math.floor()这类对象方法,或是Array.prototype.map()这类原型方法。尝试直接传入函数引用替代window["函数名字符串"]的方式也未能解决问题。
解决方案
通过将目标函数所属的对象(或原型)与函数名作为参数传入,对原函数进行包装时保留其上下文绑定,即可实现各类函数的监控:
function watchFunction(obj, fName) { let counter = 0; const originalFunction = obj[fName]; obj[fName] = (...args) => { counter++; return originalFunction.bind(obj)(...args); }; return { removeWatcher: () => (obj[fName] = originalFunction), resetCount: () => (counter = 0), getCount: () => counter, }; }
核心逻辑说明
- 接收目标函数所在的对象(如
Math、Array.prototype)和函数名作为参数 - 保存原函数引用,避免覆盖后丢失原功能
- 包装后的函数执行时自动累加计数,并通过
bind(obj)确保原函数的上下文(this指向)正确 - 返回控制方法:移除监控、重置计数、获取当前计数
使用示例
以监控Array.prototype.push为例:
// 初始化监控 const arrayPushWatcher = watchFunction(Array.prototype, "push"); let arr = []; // 初始计数:0 console.log("Array.prototype.push", arrayPushWatcher.getCount()); arr.push(1); // 执行1次后计数:1 console.log("Array.prototype.push", arrayPushWatcher.getCount()); arr.push(1); // 执行2次后计数:2 console.log("Array.prototype.push", arrayPushWatcher.getCount()); // 移除监控 arrayPushWatcher.removeWatcher(); arr.push(1); // 计数不再变化:2 console.log("Array.prototype.push", arrayPushWatcher.getCount());
内容的提问来源于stack exchange,提问作者Zintis May-Krumins
相关产品推荐
相关产品推荐

