When it comes to closures, it must have been heard, and my simple understanding follows.
To tell the truth, there are not many scenes of actual manual closures in the work, but the third-party frameworks and components used in the project are more or less used in closures.
Therefore, it is very necessary to understand closures. Oh ...
One, what is closures
In short, it is the function that can read the variables inside other functions.
due to the nature of the JS variable scope, external variables cannot be accessed externally, and external variables can be used internally.
second, the use of the scene
1. Implement a private member.
2. Protect namespaces and avoid polluting global variables.
3. Cache variables.
4. Code Reuse
let's look at an example of encapsulation:
- var person = function () {
- Variable scope is inside function, external unreachable
- 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.getname ()); The result is: LANGJT
Copy Code
Then look at common closures in loops to solve the problem of referencing external variables:
- var aLi = document.getelementsbytagname (' li ');
- For (var i=0, len=ali.length; i<len; i++) {
- Ali[i].onclick = function () {
- alert (i); Regardless of which <li> element is clicked, the pop-up value is Len, indicating that I is the same as the value for printing I after for.
- };
- }
Copy Code
After using closures:
- var aLi = document.getelementsbytagname (' li ');
- For (var i=0, len=ali.length; i<len; i++) {
- Ali[i].onclick = (function (i) {
- return function () {
- alert (i); When you click on the <li> element, the corresponding subscript will pop up.
- }
- }) (i);
- }
Copy Code
Third, the matters needing attention
1. Memory leaks
Because the closure will make the variables in the function are stored in memory, memory consumption is very large, so can not abuse closures, otherwise it will cause the performance of the Web page.
Like what:
- function foo () {
- var odiv = document.getElementById (' J_div ');
- var id = odiv.id;
- Odiv.onclick = function () {
- alert (odiv.id); There is a circular reference here, and the Odiv is still in memory after the low version of IE page closes. So try to cache the base type instead of the object.
- alert (ID);
- };
- Odiv = null;
- }
Copy Code
2. Variable naming
If the variables of the intrinsic function and the variable name of the external function are the same, then the intrinsic function cannot point to the variable with the same name as the outer function.
Like what:
- function foo (num) {
- return function (num) {
- Console.log (num);
- }
- }
- var f = new Foo (9);
- f (); Undefined
Copy Code
In fact, the above usage, the jargon called function currying, is to transform a function that accepts multiple parameters into a function that takes a single parameter (the first parameter of the initial function) and returns a new function that accepts the remaining parameters and returns the result. In essence, the features that can be cached by closures are also used, such as:
- var adder = function (num) {
- return function (y) {
- return num+y;
- };
- };
- var inc = Adder (1);
- var dec = adder (-1);
- Inc, Dec is now two new functions that will pass in parameter values (+/‐) 1
- Alert (inc (99));//100
- Alert (Dec (101));//100
- Alert (Adder (100) (2));//102
- Alert (Adder (2) (100));//102
Copy Code
Again such as Ali Yuber's Seajs Source:
- /**
- * Util-lang.js-the Minimal language enhancement
- */
- function Istype (type) {
- return function (obj) {
- return {}.tostring.call (obj) = = "[Object" + Type + "]"
- }
- }
- var IsObject = Istype ("Object");
- var isstring = Istype ("String");
Copy Code
JavaScript closures Simple Comprehension