为什么源只被调用一次?

时间:2021-01-20 02:14:19

标签: javascript html

来源

function sayHello() {
   var time = timemore();
   time();
   time();
}

function timemore(){
    var cnt = 0; 
    document.write('<br />cnt : '+cnt);
    return function(){
        if(cnt<3){
            document.write('<br />start');
            cnt++;
        }else{
            document.write('<br />end'); 
        }
    }
}
sayHello();

结果

cnt : 0
start
start

result 被调用两次 为什么 'document.write('
cnt : '+cnt);'... 只调用一次?

3 个答案:

答案 0 :(得分:1)

<块引用>

为什么 document.write('cnt : '+cnt);... 只被调用一次?

因为 document.write('<br />cnt : '+cnt); 是方法 timemore 中的一行,您只调用 timemore 一次。

让我们稍微分解一下。

在第 2 行,您调用 timemore。这将运行 timemore 函数(写出有问题的行),并返回另一个函数,您将其分配给变量 time。您返回的函数如下所示:

function(){
    if(cnt<3){
        document.write('<br />start');
        cnt++;
    }else{
        document.write('<br />end'); 
    }
}

所以,现在 time 指向这个函数。如您所见,此函数在任何时候都不会调用 document.write('<br />cnt : '+cnt);。因此,无论您调用函数 time 多少次,都不会再调用该行。

答案 1 :(得分:0)

因为 document.write('<br />cnt : '+cnt);timemore()

var time = timemore() 表示 time 将是 timemore() 的返回值

即执行timemore()后,变量time会是下面的函数

function(){
        if(cnt<3){
            document.write('<br />start');
            cnt++;
        }else{
            document.write('<br />end'); 
        }
}

所以 timemore() 实际上只执行一次。

答案 2 :(得分:0)

它被称为咖喱函数。每次调用 time() 时都会调用内部函数。如果你在内部函数中有另一个函数,你可以像 time()() 一样调用它。

Reference/Read more about currying