在这种情况下使用闭包是否有好处

时间:2014-12-10 11:01:18

标签: javascript

此代码中使用了闭包:

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();

1 个答案:

答案 0 :(得分:1)

函数myClosure将始终返回相同的值,因为var date = new Date();将仅执行一次。但是函数myNonClosure将返回当前毫秒数。所以它们并不相同。