有一个javascript函数私人跟踪它的呼叫数量 [英] Have a javascript function privately track it's number of calls

查看:119
本文介绍了有一个javascript函数私人跟踪它的呼叫数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何让一个javascript函数私下跟踪它被调用的次数。目标是能够在调试期间通过执行 func.run

I'm trying to figure out how I can have a javascript function privately track the number of times it has been called. The objective is to be able to query this value in the console during debugging by doing func.run

来在控制台中查询此值尝试:

My first attempt:

function asdf() { 
  if (!asdf.run) {
    asdf.run = 0;
  } else {
    asdf.run++;
    console.error('run: ' + asdf.run);
  }
  console.error('asdf.run def: ');
  console.error(asdf.run);
}
asdf();





这是一个很好的教训应该总是在几乎所有的javascript布尔中使用 === ,因为他们可以秘密地 ==



This is a good lesson of why one should ALWAYS aim to use === in nearly all javascript booleans, cause they could secretly be ==

推荐答案

关闭是通往这里的方法:

Closures are the way to go here:

var asdf = (function () {
    var runs = 0;
    var f = function () {
        ++runs;
        // your function here
    };
    f.runs = function () {
        return runs;
    };
    return f;
}());

用法:

asdf();
asdf();
asdf.runs(); // 2
asdf();
asdf.runs(); // 3

或者,你可以使用一个模拟框架( shameless self plug < sub>) Myrtle

Or, you could use a mocking framework like (shameless self plug) Myrtle.

这篇关于有一个javascript函数私人跟踪它的呼叫数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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