This article analyzes the concept and usage of Javascript closures with examples. Share it with everyone for your reference. The details are as follows:
When it comes to closures, everyone must have heard of them. Here is my simple understanding.
To be honest, there are not many scenarios where closures are actually written manually in daily work, but the third-party frameworks and components used in the project more or less use closures.
Therefore, it is very necessary to understand closures. Haha...
1. What is closure
In short, it is a function that can read the internal variables of other functions.
Due to the characteristics of JS variable scope, internal variables cannot be accessed from the outside, but external variables can be accessed from the inside.
2. Usage scenarios
1. Implement private members.
2. Protect the namespace and avoid polluting global variables.
3. Cache variables.
Let’s look at an example of encapsulation first:
return {
getName: function () {
return name;
},
setName: function (newName) {
name = newName;
}
}
}();
console.log(person.name); // Direct access, the result is: undefined
console.log(person.getName()); // The result is: default
console.log(person.setName("langjt"));
console.log(person.getName()); // The result is: langjt
Look at the commonly used closures in loops to solve the problem of referencing external variables:
3. Precautions
1. Memory leak
Since closures cause all variables in the function to be stored in memory, which consumes a lot of memory, closures cannot be abused, otherwise it will cause performance problems on the web page.
For example:
2. Variable naming
If the variable name of the internal function and the variable name of the external function are the same, then the internal function can no longer point to the variable with the same name of the external function.
For example:
En fait, l'usage ci-dessus, le terme professionnel est appelé currying de fonction, consiste à transformer une fonction qui accepte plusieurs paramètres en une fonction qui accepte un seul paramètre (le premier paramètre de la fonction d'origine), et renvoie les paramètres restants. . Nouvelle technologie de fonction qui prend des paramètres et renvoie un résultat. Essentiellement, il profite également de la fonction de mise en cache des fermetures, telles que :
var inc = additionneur(1);
var déc = additionneur(-1);
//inc, dec sont maintenant deux nouvelles fonctions, leur fonction est de convertir la valeur du paramètre transmis (/‐)1
alerte(inc(99));//100
alert(dec(101));//100
alert(adder(100)(2));//102
alerte(adder(2)(100));//102
Un autre exemple est le code source seaJS d'Ali Yubo :
var isObject = isType("Object");
var isString = isType("String");
J'espère que cet article sera utile à la conception de la programmation JavaScript de chacun.