首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript闭包函数

Javascript闭包函数
EN

Stack Overflow用户
提问于 2015-08-23 18:29:02
回答 3查看 134关注 0票数 0

所以我对javascript很陌生,我正在寻找一种方法来计算一个函数被执行了多少次。代码随机生成一个正方形或圆形,当您单击它(reactionTime)时,将显示该形状的显示。效果很好而且很好。但我正在寻找一种方法来跟踪一个形状被点击的次数,并最终计算每次点击平均时间的累积时间。如果有帮助的话,我来自一个很好的C++背景。

为了计算点击次数,我正在考虑添加一个闭包函数。出发地:How do I find out how many times a function is called with javascript/jquery?

代码语言:javascript
复制
    myFunction = (function(){
        var count = 0;
        return function(){
            count++
            alert( "I have been called " + count + " times");
        }
     })();

从这里开始:Function count calls

代码语言:javascript
复制
    var increment = function() {
        var i = 0;
        return function() { return i += 1; };
    };

    var ob = increment();

但是,我尝试了一个全局变量和几个闭包函数的变体,但都没有效果(查找注释)。我试着把闭包函数放到其他函数中。我也试过这样的方法:

代码语言:javascript
复制
    var increment = makeBox();

我想知道是否有人能引导我朝正确的方向前进。我会很感激的!

代码语言:javascript
复制
    var clickedTime; var createdTime; var reactionTime;

    var clicked; var avg = 0;

    avg = (avg + reactionTime) / clicked;
    document.getElementById("clicked").innerHTML = clicked;
    document.getElementById("avg").innerHTML = avg;

    function getRandomColor() {
    ....
    }

    function makeBox() { // This is the long function that makes box
        createdTime = Date.now();
        var time = Math.random();
        time = time * 3000;

        ///////// var increment = function () {
            var i = 0;
            //return function() { return i += 1; };
            i++;
            return i;
        ///////// };


        // clicked++; /////////// global variable returns NaN
        // console.log(clicked);
        // alert("Clicked: "+clicked);

        setTimeout(function() {
            if (Math.random() > 0.5) {
                document.getElementById("box").style.borderRadius="75px"; }
            else {
                document.getElementById("box").style.borderRadius="0px"; }

            var top = Math.random(); top = top * 300;
            var left = Math.random(); left = left * 500;

            document.getElementById("box").style.top = top+"px";
            document.getElementById("box").style.left = left+"px";
            document.getElementById("box").style.backgroundColor = getRandomColor();
            document.getElementById("box").style.display = "block";
            createdTime = Date.now();
        }, time);
    }

    ob = increment(); //////////////////////// I think this gives me 1 every time
    alert("Increment: "+ob); //////////////////

    document.getElementById("box").onclick = function() {
        clickedTime = Date.now();
        reactionTime= (clickedTime - createdTime)/1000;
        document.getElementById("time").innerHTML = reactionTime;
        this.style.display = "none";
        makeBox();
    }

    makeBox();
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-08-23 19:03:09

下面是一个示例,展示了闭包如何计数对函数的调用:

代码语言:javascript
复制
function add5(y) {
    //A totally normal function
    return y + 5;
}

var counter = 0, /*a counter scoped outside of the function counter function*/
    trackedAdd5 = (function (func) {
        /*This anonymous function is incrementing a counter and then calling the function it is passed*/
        return function () {
            counter++;
            /*The trick is this function returns the output of calling the passed in function (not that it is applying it by passing in the arguments)*/
            return func.apply(this, arguments);
        }
    })(add5); /*calling this tracking function by passing the function to track*/

document.getElementById('run').addEventListener('click', function () {
    /*Here we are treating this new trackedAdd5 as a normal function*/
    var y = document.getElementById('y');
    y.value = trackedAdd5(parseInt(y.value, 10));
    /*Except the outer counter variable now represents the number of times this function has been called*/
    document.getElementById('counter').value = counter;
});
代码语言:javascript
复制
<label> <code>y = </code> 
    <input id='y' value='0' />
    <button id='run'>add5</button>
</label>
<br/>
<label><code>add5()</code> was called
    <input readonly id='counter' value='0' />times</label>

票数 0
EN

Stack Overflow用户

发布于 2015-08-23 18:45:24

你有一些问题,但要回答你的问题:

  • 您没有将clicked定义为数字(或任何其他类型),因此尝试在undefined上执行操作会很好地返回NaN...because,而不是数字。
  • 您的第二次尝试var i = 0;将无法工作,因为每个函数调用都重新定义了i

您应该能够使用您的gobal变量clicked,只要您将它设置为零。

票数 2
EN

Stack Overflow用户

发布于 2015-08-23 19:13:46

代码语言:javascript
复制
makeBox.click = 0; // define the function's counter outside the function
makeBox.click++; // replace the `i` usage with this inside the function

关于ob = increment();:它被错误地使用(多次重新定义ob );

代码语言:javascript
复制
var ob = increment(); // define it once
ob(); // increments the counter

// another way to define `increment`:
var increment = (function () {
    var i = 0;
    return function () {
        return i += 1;
    };
})();

ob = increment(); // ob becomes 1 initially
ob = increment(); // ob becomes 2, etc.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32170004

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档