Skip to content Skip to sidebar Skip to footer

What Can Javascript Closures Be Used For?

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

Solution 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);

Solution 2:

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

functionSingleton() {
    // cached instancevar instance = this;

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

    Singleton = function() {
        return instance;
    }
}

var singleton1 = newSingleton();
var singleton2 = newSingleton();

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 notto the outside code.

Post a Comment for "What Can Javascript Closures Be Used For?"