This article analyzes the concept and usage of Javascript closures. Share it for your reference. The details are as follows:
When it comes to closures, I believe everyone has heard of them. Let me tell you my simple understanding below.
To be honest, there are not many scenarios for writing closures manually in daily work, but the third-party frameworks and components used in the project use more or less closures.
Therefore, it is very necessary to understand closures. hehe...
1. What is a closure
In short, it is a function that can read variables inside other functions.
Due to the scope of JS variables, internal variables cannot be accessed externally, and external variables can be externally.
2. Use scenarios
1. Implement private members.
2. Protect namespaces to avoid polluting global variables.
3. Cache variables.
Let's first look at an example of encapsulation:
Copy the code as follows: var person = function () {
// The scope of the variable is inside the function and cannot be accessed outside
var name = "default";
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
Let’s look at the common closures in loops to solve the problem of referencing external variables:
The code copy is as follows: var aLi = document.getElementsByTagName('li');
for (var i=0, len=aLi.length; i<len; i++) {
aLi[i].onclick = function() {
alert(i); // No matter which element you click on, the pop-up value is len, indicating that the value of i here and the value of i printed after for is the same.
};
}
After using the closure:
The code copy is as follows: var aLi = document.getElementsByTagName('li');
for (var i=0, len=aLi.length; i<len; i++) {
aLi[i].onclick = (function(i) {
return function() {
alert(i); // Click the <li> element at this time and the corresponding subscript will pop up.
}
})(i);
}
3. Things to note
1. Memory Leak
Since closures will cause all variables in the function to be stored in memory, and the memory consumption is very large, closures cannot be abused, otherwise it will cause performance problems of the web page.
for example:
Copy the code as follows: function foo() {
var oDiv = document.getElementById('J_DIV');
var id = oDiv.id;
oDiv.onclick = function() {
// alert(oDiv.id); There is a circular reference here. ODiv is still in memory after the IE low version page is closed. So cache primitive types instead of objects as much as possible.
alert(id);
};
oDiv = null;
}
2. Variable Naming
If the variable of the inner function and the variable name of the outer function are the same, the inner function can no longer point to the variable with the same name as the outer function.
for example:
Copy the code as follows: function foo(num) {
return function(num) {
console.log(num);
}
}
var f = new foo(9);
f(); // undefined
In fact, the above usage is called function currying, which is the technique of converting a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function), and returning a new function that accepts the remaining parameters and returns the result. In essence, it also utilizes features that closures can be cached, such as:
Copy the code as follows: var adder = function(num) {
return function(y) {
return num+y;
};
};
var inc = add(1);
var dec = add(-1);
//inc, dec is now two new functions, which is used to pass in parameter value (+/) 1
alert(inc(99));//100
alert(dec(101));//100
alert(adder(100)(2));//102
alert(adder(2)(100));//102
For example, in the seaJS source code of Alibaba Yubo:
Copy the code as follows:/**
* util-lang.js - The minimum language enhancement
*/
function isType(type) {
return function(obj) {
return {}.toString.call(obj) == "[object " + type + "]"
}
}
var isObject = isType("Object");
var isString = isType("String");
I hope this article will be helpful to everyone's JavaScript programming.