此代码中使用了闭包:
window.onload = function() {
var output = document.getElementById('Output');
var closure = myClosure();
output.innerHTML = closure();
window.setTimeout(function() {
output.innerHTML += '<br />' + closure();
}, 500);
}
function myNonClosure() {
var date = new Date();
return date.getMilliseconds();
}
function myClosure() {
var date = new Date();
return function() {
return date.getMilliseconds();
}
}
我只是想知道使用闭包版本的函数对非闭包函数有什么好处?
output.innerHTML = myNonClosure();
答案 0 :(得分:1)
函数myClosure
将始终返回相同的值,因为var date = new Date();
将仅执行一次。但是函数myNonClosure
将返回当前毫秒数。所以它们并不相同。