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');
}
}