代码改变世界

JavaScript Patterns 4.3 Returning Functions

2014-06-09 22:54  小郝(Kaibo Hao)  阅读(281)  评论(0编辑  收藏  举报

Use closure to store some private data, which is accessible by the returned function but not to the outside code.

var setup = function () {

    var count = 0;

    return function () {

            return (count += 1);

    };

}; 

// usage

var next = setup();

next(); // returns 1

next(); // 2

next(); // 3