Javascript 为什么源只调用一次?

Javascript 为什么源只调用一次?,javascript,html,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 />star

来源

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();
结果被调用两次 为什么“document.write('
cnt:'+cnt);”。。。只打过一次电话

为什么是
document.write('cnt:'+cnt)。。。只打过一次电话


因为
document.write('
cnt:'+cnt)
是方法
timemore
中的一行,您只能调用
timemore
一次

让我们把它分解一下

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

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

如果(cnt因为
document.write('
cnt:'+cnt);
timemore()中

var time=timemore()

也就是说,在执行
timemore()
之后,变量
time
将是以下函数

function(){

if(cnt称为curry函数。每次调用time()时都会调用内部函数。如果内部函数中有另一个函数,则可以像time()一样调用它

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