简体   繁体   English

实现函数的闭包和自调用

[英]Implementing Closures and Self invocation of functions

In this, I am trying to assign the start time in the beginning and when I will click on the page it should return me the time spent but I am getting 0 always. 在这种情况下,我试图在开始时指定开始时间,当我单击页面时,它应该返回我所花费的时间,但我总是得到0。 I am not understanding that where I might have gone. 我不明白我可能去了哪里。 Need your help. 需要你的帮助。

     var timeSpent = (function(){
        var time    = new Date();
        var timeRun = false,
            startTime = time.getTime();

        return function(){ // call this function by timeSpent()(); 
            return time.getTime() - startTime;
        }
    })();

    addEventListener("click", function(){
        console.log(timeSpent());
    })

You need to calculate the present time inside the inner function 您需要在内部函数中计算当前时间

 var timeSpent = (function(){ var time = new Date(); var timeRun = false, startTime = time.getTime(); return function(){ // call this function by timeSpent()(); return (new Date()).getTime() - startTime; } })(); addEventListener("click", function(){ console.log(timeSpent()); }) 

time is a date. time是一个日期。 Every time you call getTime() on it, you will get the same value. 每次在其上调用getTime()时,您将获得相同的值。

So startTime and time.getTime() will always be the same. 因此, startTimetime.getTime()将始终相同。

You need to replace time.getTime() inside the returned function with something which will get the current time. 您需要将返回的函数中的 time.getTime()替换为将获取当前时间的内容。 (new Date()).getTime()

 var timeSpent = (function() { var time = new Date(); var timeRun = false, startTime = time.getTime(); return function() { // call this function by timeSpent()(); return (new Date()).getTime() - startTime; } })(); addEventListener("click", function() { console.log(timeSpent()); }) 

Your function timeSpent() is evaluated as (you can check it by logging the function in console) 您的函数timeSpent()的评估为(您可以通过在控制台中登录该函数进行检查)

return time.getTime() - startTime;

As, startTime = time.getTime() initially. 作为, startTime = time.getTime()最初。 Therefore, the above return statement will evaluted to 0. In order to get the current time, you will have to call new Date().getTime() 因此,上述return语句的计算结果为0。为了获取当前时间,您将必须调用new Date().getTime()

 var timeSpent = (function(){ var time = new Date(); var timeRun = false, startTime = time.getTime(); return function(){ // call this function by timeSpent()(); return new Date().getTime() - startTime; } })(); addEventListener("click", function(){ console.log(timeSpent()); }) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM