使用JavaScript计数函数调用 [英] Count functions calls with JavaScript

查看:176
本文介绍了使用JavaScript计数函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:我有很多功能,并使用它们很多次。
我需要为每个函数计数调用。
最好的做法是什么?

For example: I have a lot of functions and use them many times. I need to count calls for each function. What is the best practice to make it?

起初我想我需要闭包,但是我不能以正确的方式实现它。 p>

At first i thought i need closures, but I can't implement it in a right way.

推荐答案

在最简单的情况下,你可以用一个剖析包装来装饰每个函数:

In the simplest case, you can decorate each function with a profiling wrapper:

_calls = {}

profile = function(fn) {
    return function() {
        _calls[fn.name] = (_calls[fn.name] || 0) + 1;
        return fn.apply(this, arguments);
    }
}

function foo() {
    bar()
    bar()
}

function bar() {
}

foo = profile(foo)
bar = profile(bar)

foo()
foo()

document.write("<pre>" + JSON.stringify(_calls,0,3));

调试,你可能会更好地使用专用的分析器(通常位于浏览器的控制台)。

For serious debugging, you might be better off with a dedicated profiler (usually located in your browser's console).

这篇关于使用JavaScript计数函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆