问题
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!
回答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);
回答2:
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.
来源:https://stackoverflow.com/questions/15673925/what-can-javascript-closures-be-used-for