2016-03-01 76 views
2

我想了解在JavaScript关闭和我碰到下面的例子就是:的Javascript关闭返回功能

function counter() { 
    var count = 0; 
    return function() { 
     alert(count++); 
    } 
} 
var count = counter(); 
count(); 
count(); 
count(); 

这对我来说很有意义,我的问题是,为什么不这项工作?

var count = function() { 
    var count = 0; 
    return function() { 
     alert(count++); 
    } 
}; 
count(); 
count(); 
count(); 

对我来说,它看起来像它应该是完全一样的事情,但也许我只是缺少明显的东西,请帮助。

回答

1

,我会尽量给你的代码一个不错的解释权:

function counter() { 
    var count = 0; 

    // By calling the function counter (adding a '()' after its name) you are returning a brand new anonymous function 
    return function() { // **Reference 1** 
     alert(count++); 
    } 
} 

// Here, the count variable is actually the anonymous function you returned in the **Reference 1** 
var count = counter(); 

// In this line, you are calling the anonymous function (adding the '()' after its new name 'count') 
count(); 

上述解释解释为什么这个工程。因为,首先你调用了一个函数,它返回一个匿名函数并将其分配给变量计数。然后你通过在其名称后面加上'()'来调用该函数,该函数执行alert(count++)

现在,为什么其他示例不起作用?我想,现在是很明显:

var count = function() { 
    var count = 0; 
    return function() { // **Reference 2** 
     alert(count++); 
    } 
}; 

// Here you are calling the count function which returns the anonymous function in the line **Reference 2**. 
count(); // So, long story short, this call only returns the anonymous function. 

你应该尝试第二“()”后增加:count()();。这应该也可以,因为第一个'()'返回匿名函数,第二个执行返回的匿名函数。

希望这会有所帮助!

+0

非常感谢大家,所有的答案都很有帮助,我只是很感激在这里额外付出代价,并在代码中解释答案,我现在完全明白了。 – SeptimaEspada

+0

很棒@SeptimaEspada。这是一个非常简单的概念,对于Javascript高级编程非常有用。非常乐意帮助你! :) – wilsotobianco

0

在使用闭包之前,必须调用外部函数来创建闭包并获取返回的内部函数,然后保留该返回结果,然后可以调用后续时间来使用闭包。因此,在第二个示例中,您必须致电count()并保留其返回结果,然后将该返回结果用于后续调用。

如果改成这样(看起来几乎一样的第一个例子)你的第二个示例将工作:

// log output for purposes of the snippet 
 
function log(x) { 
 
    var div = document.createElement("div"); 
 
    div.innerHTML = x; 
 
    document.body.appendChild(div); 
 
} 
 

 
var counter = function() { 
 
    var count = 0; 
 
    return function() { 
 
     log(count++); 
 
    } 
 
}; 
 
// get the inner function and create the closure 
 
var count = counter(); 
 
count(); 
 
count(); 
 
count();

正如你可以看到这只不同于你第一个例子是counter是一个函数表达式,而不是函数定义。除了定义counter的时间之外,第二个代码示例没有区别,因此实现需要相同。

+0

是的,这很有道理,谢谢。 – SeptimaEspada

1

为了让你的第二个方法来工作,你将需要调用返回的功能是这样的:

var count = function() { 
    var count = 0; 
    return function() { 
     alert(count++); 
    } 
}; 
count()(); 

但是,这样做,你的计数量不会增加,因为它没有被任何地方像存储在第一个示例中,变量count包含该函数。

所以,如果你想保留计数的值,使用在那里你说var count = counter()

希望第一种方法是清除的东西了!

+0

它呢,谢谢! – SeptimaEspada