--- title: Chiusure slug: Web/JavaScript/Closures translation_of: Web/JavaScript/Closures original_slug: Web/JavaScript/Chiusure ---
Una closure è la combinazione di una funzione e dello stato nella quale è stata creata (ambito lessicale). In altre parole, una closure consente a una funzione interna di accedere allo scope della funzione che la racchiude. In Javascript le closure sono create ogni volta che una funzione viene creata, al momento della creazione della funzione stessa.
Considerate la seguente:
function init() { var name = "Mozilla"; // name è una variabile locale creata da init function displayName() { // displayName() è una funzione interna, una chiusura alert(name); // utilizza la variabile dichiarata nella funzione padre } displayName(); } init();
init()
crea una variabile locale name
e poi una funzione chiamata displayName()
. displayName()
è una funzione interna che è definita dentro init()
ed è disponibile solo all'interno del corpo di quella funzione. displayName()
non ha proprie variabili locali. Tuttavia, poiché le funzioni interne hanno accesso alle variabili di quelle esterne, displayName()
può accedere alla variabile name
dichiarata nella funzione genitore, init()
Tuttavia verrebbero usate le variabili locali in displayName()
, se esistessero.
{{JSFiddleEmbed("https://jsfiddle.net/78dg25ax/", "js,result", 200)}}
Esegui il codice e verifica che funziona. Questo è un esempio di lexical scoping: in JavaScript, la visibilità (scope) di una variabile è definita dalla sua posizione all'interno del codice sorgente (si evince dal codice stesso [lexically]) e le funzioni innestate hanno accesso a variabili dichiarate nella funzione esterna (outer scope).
Considerate ora l'esempio seguente:
function makeFunc() { var name = "Mozilla"; function displayName() { alert(name); } return displayName; } var myFunc = makeFunc(); myFunc();
L'esecuzione di questo codice ha esattamente lo stesso effetto dell'esempio precedente della funzione init(): la stringa "Mozilla" verrà visualizzata in una casella di avviso JavaScript. La cosa differente ed interessante, è che la funzione interna displayName() viene restituita dalla funzione esterna prima di essere eseguita.
A un primo sguardo sembrerebbe controintuitivo che il codice funzioni ancora. In alcuni linguaggi di programmazione le variabili locali interne a una funzione esistono solo per la durata dell'esecuzione della funzione stessa. Una volta che makeFunc()
ha terminato la propria esecuzione, ci si potrebbe aspettare che la variabile name non sia più accessibile. Tuttavia, poiché il codice funziona ancora, è ovvio che in JavaScript non è il caso.
La ragione è che le funzioni in JavaScript formano closures. Una closure è la combinazione di una funzione e dell'ambito lessicale in cui questa funzione è stata dichiarata. In questo caso, myFunc
è un riferimento all'istanza della funzione displayName creata quando makeFunc
è eseguita.
La soluzione di questo rompicampo è che myFunc
è diventata una closure. Una closure è uno speciale tipo di oggetto che combina due cose: una funzione e l'ambito in cui questa è stata creata. L'ambito consiste in qualsiasi variabile locale che era nel suo scope nel momento in cui la closure è stata creata. In questo caso, myFunc
è una closure che incorpora sia la funzione displayName
che la stringa "Mozilla", già esistente quando la closure è stata creata.
Ecco un esempio leggermente più interessante — una funzione makeAdder
:
function makeAdder(x) { return function(y) { return x + y; }; } var add5 = makeAdder(5); var add10 = makeAdder(10); console.log(add5(2)); // 7 console.log(add10(2)); // 12
In questo esempio, abbiamo definito una funzione makeAdder(x)
che prende un singolo argomento x
e restituisce una nuova funzione. La funzione restituita prende un singolo argomento y
, e restituisce la somma tra x
e y
.
In sostanza, makeAdder
è una factory function — crea funzioni che possono aggiungere uno specifico valore come argomento. Nell'esempio sopra usiamo la nostra factory function per creare due nuove funzioni — una che aggiunge 5 ai suoi argomenti, e una che aggiunge 10.
add5
e add10
sono entrambe closures. Condividono la stessa definizione del corpo della funzione, ma memorizzano diversi ambienti. Nell'ambiente di add5
, x
vale 5. Per quanto riguarda add10
, x
vale 10.
That's the theory of closures — but are closures actually useful? Let's consider their practical implications. A closure lets you associate some data (the environment) with a function that operates on that data. This has obvious parallels to object oriented programming, where objects allow us to associate some data (the object's properties) with one or more methods.
Consequently, you can use a closure anywhere that you might normally use an object with only a single method.
Situations where you might want to do this are particularly common on the web. Much of the code we write in web JavaScript is event-based — we define some behavior, then attach it to an event that is triggered by the user (such as a click or a keypress). Our code is generally attached as a callback: a single function which is executed in response to the event.
Here's a practical example: suppose we wish to add some buttons to a page that adjust the text size. One way of doing this is to specify the font-size of the body element in pixels, then set the size of the other elements on the page (such as headers) using the relative em unit:
body { font-family: Helvetica, Arial, sans-serif; font-size: 12px; } h1 { font-size: 1.5em; } h2 { font-size: 1.2em; }
Our interactive text size buttons can change the font-size property of the body element, and the adjustments will be picked up by other elements on the page thanks to the relative units.
Qui c'è il codice JavaScript:
function makeSizer(size) { return function() { document.body.style.fontSize = size + 'px'; }; } var size12 = makeSizer(12); var size14 = makeSizer(14); var size16 = makeSizer(16);
size12
, size14
, and size16
are now functions which will resize the body text to 12, 14, and 16 pixels, respectively. We can attach them to buttons (in this case links) as follows:
document.getElementById('size-12').onclick = size12; document.getElementById('size-14').onclick = size14; document.getElementById('size-16').onclick = size16;
<a href="#" id="size-12">12</a> <a href="#" id="size-14">14</a> <a href="#" id="size-16">16</a>
{{JSFiddleEmbed("https://jsfiddle.net/vnkuZ/","","200")}}
Languages such as Java provide the ability to declare methods private, meaning that they can only be called by other methods in the same class.
JavaScript does not provide a native way of doing this, but it is possible to emulate private methods using closures. Private methods aren't just useful for restricting access to code: they also provide a powerful way of managing your global namespace, keeping non-essential methods from cluttering up the public interface to your code.
Here's how to define some public functions that can access private functions and variables, using closures which is also known as the module pattern:
var counter = (function() { var privateCounter = 0; function changeBy(val) { privateCounter += val; } return { increment: function() { changeBy(1); }, decrement: function() { changeBy(-1); }, value: function() { return privateCounter; } }; })(); console.log(counter.value()); // logs 0 counter.increment(); counter.increment(); console.log(counter.value()); // logs 2 counter.decrement(); console.log(counter.value()); // logs 1
There's a lot going on here. In previous examples each closure has had its own environment; here we create a single environment which is shared by three functions: counter.increment
, counter.decrement
, and counter.value
.
The shared environment is created in the body of an anonymous function, which is executed as soon as it has been defined. The environment contains two private items: a variable called privateCounter
and a function called changeBy
. Neither of these private items can be accessed directly from outside the anonymous function. Instead, they must be accessed by the three public functions that are returned from the anonymous wrapper.
Those three public functions are closures that share the same environment. Thanks to JavaScript's lexical scoping, they each have access to the privateCounter
variable and changeBy
function.
You'll notice we're defining an anonymous function that creates a counter, and then we call it immediately and assign the result to the counter
variable. We could store this function in a separate variable makeCounter
and use it to create several counters.
var makeCounter = function() { var privateCounter = 0; function changeBy(val) { privateCounter += val; } return { increment: function() { changeBy(1); }, decrement: function() { changeBy(-1); }, value: function() { return privateCounter; } } }; var counter1 = makeCounter(); var counter2 = makeCounter(); alert(counter1.value()); /* Alerts 0 */ counter1.increment(); counter1.increment(); alert(counter1.value()); /* Alerts 2 */ counter1.decrement(); alert(counter1.value()); /* Alerts 1 */ alert(counter2.value()); /* Alerts 0 */
Notice how each of the two counters maintains its independence from the other. Its environment during the call of the makeCounter()
function is different each time. The closure variable privateCounter
contains a different instance each time.
Using closures in this way provides a number of benefits that are normally associated with object oriented programming, in particular data hiding and encapsulation.
Prior to the introduction of the let
keyword in ECMAScript 6, a common problem with closures occurred when they were created inside a loop. Consider the following example:
<p id="help">Helpful notes will appear here</p> <p>E-mail: <input type="text" id="email" name="email"></p> <p>Name: <input type="text" id="name" name="name"></p> <p>Age: <input type="text" id="age" name="age"></p>
function showHelp(help) { document.getElementById('help').innerHTML = help; } function setupHelp() { var helpText = [ {'id': 'email', 'help': 'Your e-mail address'}, {'id': 'name', 'help': 'Your full name'}, {'id': 'age', 'help': 'Your age (you must be over 16)'} ]; for (var i = 0; i < helpText.length; i++) { var item = helpText[i]; document.getElementById(item.id).onfocus = function() { showHelp(item.help); } } } setupHelp();
{{JSFiddleEmbed("https://jsfiddle.net/v7gjv/", "", 200)}}
The helpText
array defines three helpful hints, each associated with the ID of an input field in the document. The loop cycles through these definitions, hooking up an onfocus event to each one that shows the associated help method.
If you try this code out, you'll see that it doesn't work as expected. No matter what field you focus on, the message about your age will be displayed.
The reason for this is that the functions assigned to onfocus
are closures; they consist of the function definition and the captured environment from the setupHelp
function's scope. Three closures have been created, but each one shares the same single environment. By the time the onfocus
callbacks are executed, the loop has run its course and the item variable (shared by all three closures) has been left pointing to the last entry in the helpText
list.
One solution in this case is to use more closures: in particular, to use a function factory as described earlier on:
function showHelp(help) { document.getElementById('help').innerHTML = help; } function makeHelpCallback(help) { return function() { showHelp(help); }; } function setupHelp() { var helpText = [ {'id': 'email', 'help': 'Your e-mail address'}, {'id': 'name', 'help': 'Your full name'}, {'id': 'age', 'help': 'Your age (you must be over 16)'} ]; for (var i = 0; i < helpText.length; i++) { var item = helpText[i]; document.getElementById(item.id).onfocus = makeHelpCallback(item.help); } } setupHelp();
{{JSFiddleEmbed("https://jsfiddle.net/v7gjv/1/", "", 300)}}
This works as expected. Rather than the callbacks all sharing a single environment, the makeHelpCallback
function creates a new environment for each one in which help
refers to the corresponding string from the helpText
array.
It is unwise to unnecessarily create functions within other functions if closures are not needed for a particular task, as it will negatively affect script performance both in terms of processing speed and memory consumption.
For instance, when creating a new object/class, methods should normally be associated to the object's prototype rather than defined into the object constructor. The reason is that whenever the constructor is called, the methods would get reassigned (that is, for every object creation).
Consider the following impractical but demonstrative case:
function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); this.getName = function() { return this.name; }; this.getMessage = function() { return this.message; }; }
The previous code does not take advantage of the benefits of closures and thus could instead be formulated:
function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); } MyObject.prototype = { getName: function() { return this.name; }, getMessage: function() { return this.message; } };
However, redefining the prototype is not recommended, so the following example is even better because it appends to the existing prototype:
function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); } MyObject.prototype.getName = function() { return this.name; }; MyObject.prototype.getMessage = function() { return this.message; };
Il codice sopra può essere riscritto meglio in un modo più pulito, con lo stesso risultato:
function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); } (function() { this.getName = function() { return this.name; }; this.getMessage = function() { return this.message; }; }).call(MyObject.prototype);
In the two previous examples, the inherited prototype can be shared by all objects and the method definitions need not occur at every object creation. See Details of the Object Model for more details.