开发者

javascript closure advantages?

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 开发者_JAVA百科main advantages of using it.


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.


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


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.


As we know, the variables that are defined in functions, have local scope. We can't access them from outside of the function.

Problem 1:

local variables are created when the function is called and they will be destroyed when the function's task is finished. It means local variables have shorter life time than global variables. We may use global variables to overcome that issue.

Global variables are available when the program starts and are destroyed when it ends. They are also available throughout the program.

Problem 2:

Since global variables are accessible throughout the program, they are prone to change from everywhere.

What do we want?

We want to have data persistency + data encapsulation.

We can achieve them by using Closures. By using a closure we can have private variables that are available even after a function's task is finished.

Example:

function initCounter() {
  let counter = 0;

  return function () {
    return ++counter;
  }
}

// Each counter is persistent
const countJumps = initCounter();
countJumps();
countJumps();
alert("Jumps count is: " + countJumps());

const countClicks = initCounter();
countClicks();
countClicks();
countClicks();
countClicks();
alert("Clicks count is: " + countClicks());


// Each counter is isolated
alert(counter); // Error: counter is not defined

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜