1

I've been wondering for a while - what can JavaScript closures be used for?

I know how to write them and I know how they work, but I just can't get the idea of how they can be used.

function closure() {
  var name = "John";
  function displayName() {
    return 'Hello, ' + name;
  }
  return displayName;
}

So far I only found one use for them - encapsulating data, so it won't be visible outside the function.

But what else can they be used for? Should I write OOP with closures? Do I need to put all my code inside a closure so it wont mess the global scope?

Any clarifications are highly appreciated!

4
  • 3
    can be used for data persistence Commented Mar 28, 2013 at 3:55
  • 1
    So other functions can't mess up the variables. Commented Mar 28, 2013 at 3:57
  • Isn't "encapsulating data" (including functions) itself a BIG use in JS? Commented Mar 28, 2013 at 3:57
  • Hiding data and persisting data via "closed over" variables - as opposed to object properties. "OOP" is orthogonal to closures. The "Module Pattern" is designed to avoid messing with the global scope: however, it doesn't mandate the use of closures. Commented Mar 28, 2013 at 3:59

2 Answers 2

1

Can also be used to protect your code inside the colsure against naming conflicts between different libraries outside the closure. Ex whenever I create a JQuery plugin I create it as a self calling closure where I pass In "JQuery", but can safely refer to $ inside the closure because of the local scope of the named $ variable in my function definition. Even if there are other libraries using the $ variable for a different purpose

(function($){ //use $ safely inside the closure })
(jQuery);
Sign up to request clarification or add additional context in comments.

Comments

1

Personally, besides obvious things like encapsulating or creating private contexts, I like Singleton JavaScript Design Pattern:

function Singleton() {
    // cached instance
    var instance = this;

    //proceed as normal - adding some variables
    this.variable1 = 1000;
    this.variable2 = 3000000;

    Singleton = function() {
        return instance;
    }
}

var singleton1 = new Singleton();
var singleton2 = new Singleton();

if(singleton1 === singleton2) {
    console.log("Singleton works :)");
}
else {
    console.log("Singleton doesn't work :/");
}

You can paste this code directly into Chrome JavaScript console.

Of course you can tweak it to suit your needs. There is also some drawback - you can overwrite Singleton function, and you will not be able to access instance anymore. But this is another problem.

I found it a long time ago in JavaScript Patterns book by Stoyan Stefanov (O'Reilly) . Check this out as there are other useful design patterns and examples of closures application. According to this book:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.