javascript closure advantages?

前端 未结 4 1191
别那么骄傲
别那么骄傲 2020-12-24 03:19

Whats the main purpose of Closures in JS. Is it just used for public and private variables? or is there something else that I missed. I am trying to unders

4条回答
  •  再見小時候
    2020-12-24 03:29

    I think the best phrase to sum up the purpose of closures would be:

    Data Encapsulation

    With a function closure you can store data in a separate scope, and share it only where necessary.

    If you wanted to emulate private static variables, you could define a class inside a function, and define the private static vars within the closure:

    (function () {
        var foo;
        foo = 0;
        function MyClass() {
            foo += 1;
        }
        MyClass.prototype = {
            howMany: function () {
                return foo;
            }
        };
        window.MyClass = MyClass;
    }());
    

提交回复
热议问题