accessing variables in javascript closures

白昼怎懂夜的黑 提交于 2019-12-11 11:07:10

问题


var add = (function () {
    var counter = 0;
    return function () { 
        var reset = function() {
            counter = 0;
        }
        return counter += 1;
    }
})();

This is a self-invoking function that creates a "private" variable. How would I create a function reset that will reset the counter to 0? I've tried declaring the function inside the closure, but when I call it using add.reset(), it tells me this method is undefined.

Any help in understanding is appreciated!

来源:https://stackoverflow.com/questions/31642931/accessing-variables-in-javascript-closures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!