如何跟踪同一功能的多次运行? [英] How can I keep track of multiple runs of the same function?

查看:49
本文介绍了如何跟踪同一功能的多次运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的功能:

function run(arg) {
    if (!window.alreadyRun) init();
    window.alreadyRun = true;
    /* more code */
}

您明白了,我正在尝试弄清是否是第一次调用函数.

You get the idea, I'm trying to figure out if it's the first time a function is called.

是否有更好的方法可以做到这一点?不使用全局变量?像这样:

Is there a better way to do this? Without using globals? Something like this:

function run(arg) {
    var ranAlready;
    if (!ranAlready) init();
    ranAlready = true;
    /* more code */
}

推荐答案

这将返回一个函数,该函数带有名为 runCount 的变量,该变量将保存被调用的次数.

This will return a function, with a variable called runCount which will hold the number of times it was called.

var yourFunction = function() {
    var runCount = 0;

    return function() {
        console.log(runCount);
        runCount++;
    }  

}

var a = yourFunction();

a(); // runCount: 0
a(); // runCount: 1
a(); // runCount: 2
a(); // runCount: 3

在jsFiddle上查看.

如果只想运行init类型的函数,则可以将代码放在返回内部函数的上方.在返回内部函数之前,它将被调用一次,并且其范围将保留到其外部函数.

If you just want to run an init type function, you could place the code above returning the inner function. It will be called once before returning the inner function, and its scope will retain to its outer function.

这篇关于如何跟踪同一功能的多次运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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