javascript closure advantages?

2019-02-01 02: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 understand closure and really want to know what are the main advantages of using it.

回答1:

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


回答2:

Closures have to do with how javascript is scoped. To say it another way, because of the scoping choices (i.e. lexical scoping) the javascript designers made, closures are possible.

The advantage of closures in javascript is that it allows you to bind a variable to an execution context.

var closedIn = {};

var f = function(){
   closedIn.blah = 'blah'; // closedIn was just "closed in" because I used in the function, but it was defined outside the function.
}

in that example, you have a normal object literal called closedIn. It is accessed in a function. Because of that, javascript knows it has to bring closedIn everywhere it brings the function f, so it is available to f.

The this keyword is tricky. this is always a reference to the execution scope. You can capture the this of one context to use in another context as follows:

var that = this;
var f = function(){
    that.somethingOnThat();
   // `this` means the scope f, `that` means whatever 'this' was when defined outside of the function
}

This trick can be very useful somethings, if you are coding object oriented javascript and want a callback to have access to some external scope.

To quote from a Javascript book:

"Functions in JavaScript are lexically rather than dynamically scoped. This means that they run in the scope in which they are defined, not the scopee from which they are executed. When a function is defined, the current scope chain is saved and becomes part of the internal state of the function."

So the clear advantage is that you can bring any object (functions, objects, etc) along with the scope chain as far as is necessary. This is can also be considered a risk, because your apps can easily consume lots of memory if you are not careful.



回答3:

Closures are necessary in javascript due to the fact that most API's that require callback functions (for instance, an "onclick" function) do not provide other mechanisms to send parameters to those callback functions (or to explicitly set the "this" pointer). Instead, you need to use closures to allow the callback to access variables in the "parent" function.

I personally wish that they weren't necessary, since they can be hard to understand, make for hard to read code (it's not always clear what exactly is in scope), and make for weird bugs. Instead I wish there was a standard for callbacks that allowed you to send parameters, etc. But I accept that I am in the minority in this view.