Understanding of javascript closures

Source: Internet
Author: User
Tags javascript closure example

Understanding of javascript closures
Closure is a difficult but important point of knowledge in Javascript. 1. First, we need to know that the variable scope chain has two scopes: global variables and local variables. The variables in no function are defined as global variables and the variables defined in the function are local variables. Note that the var keyword must be used when defining variables in the function, variables without the var keyword are global variables. Every piece of code in javascript has an associated scope chain. This scope chain is an object list or linked list that defines the variables in the code "Scope. The scope of top-level code consists of global variables. The scope chain of a function that does not contain nesting has two objects: one is the defined function parameter and the other is the global variable object; the scope chain of nested functions has three objects: function parameters and local variables-external function parameters and local variables-global variables. A function can access objects in the scope chain. Therefore, a function can access global variables, but in turn cannot access local variables in a function outside the function. Var a = 1; function wai () {alert (a); var m = 10; n = 20;} wai (); // => 1; the global variable alert (m) can be accessed inside the function; // => error; the error alert (n) is returned when the local variable of the external function is accessed; // => 20; variables defined in the function do not use the var keyword. Therefore, they are global variables and can be accessed externally. 2. How to read local variables from the outside? Sometimes, we need to access the local variables in the function board externally, at this time, we need to use a work und to implement it. Using the features of javascript variable scope, we define sub-functions in the function, and the sub-functions can access the variables in the parent function. function wai () {var m = 10; function nei () {alert (m) ;}return nei ;}var f = wai (); nei (); // => error; nei () is a local variable, f (); // => 10; 3. The nei () function of the code above the closure is a closure, A closure is a function that can read local variables within a function. It is a function defined inside a function and can be considered as a bridge between the function and the function. The closure has two functions: one is to read the internal variables of the function mentioned earlier, and the other is to store these local variables in the memory, so that the variable data can be shared with function wai () {var m = 99; function nei () {alert (m); m ++;} return nei;} var f = wai (); f (); // => 99; f (); // => 100; f (); // => 101; when the preceding instance is running the wai () function, the variable m is saved to the memory. Execute f () to read the m value, but the direct alert (m) is not allowed! We can also pass parameters to the closure function, as shown in the following example, to define an anonymous function and return a closure function, which adds the input parameters to the local variable I in the anonymous function, and auto-increment I; var wai = (function () {var I = 0; return function (num) {num + = I; alert (num ); I ++ ;}}) (); wai (1); // 1wai (2); // 3wai (3); // 5 to better understand closures, let's look at the following example: Now I want to define a function. This function returns an array, and each element of the array is a function, each function will pop up the corresponding index value. We may write function box () {var arr = []; for (I = 0; I <5; I ++) in this way) {arr [I] = function () {return I ;}} return arr ;}var a = box (); alert (); // => alert (a [0] (); // => 5; alert (a [1] (); // => 5; The above code found that all pop-up items are 5, instead of the expected, and 4, this is because I is also a local variable in the memory. When we run a [0] (), the I value is already 5, the value of I is constantly increasing throughout the running process of the box () function. Solution: function box () {var arr = []; for (var I = 0; I <5; I ++) {arr [I] = (function (num) {return function () {return num ;}}) (I) ;}return arr ;}var arr = box (); for (var I = 0; I <5; I ++) {alert (arr [I, 4} 4. Precautions for using closures 1) because the closure will make the variables in the function be saved in the memory, the memory consumption is very high, so the closure cannot be abused, otherwise, it may cause webpage performance problems and may cause memory leakage in IE. The solution is to delete all unused local variables before exiting the function. 2) The closure changes the value of the internal variable of the parent function outside the parent function. Therefore, if you use the parent function as an object, use the closure as its Public Method, and use internal variables as its private value ), be sure not to change the variable value of the parent function. 5. Below are several questions about closures. If you can understand the running results of the code below, you should understand the operating mechanism of closures. Js Code var name = "The Window"; var object = {name: "My Object", getNameFunc: function () {return this. name; // => this of the nested function is a global variable or undefined and does not inherit this of the parent function. }}; alert (object. getNameFunc (); // The Window above outputs "The window" because this does not inherit The parent function this in nested functions, the value is a global variable or undefined (under ECMAScript5). Therefore, the name variable of the global object is returned. The code for returning The object name attribute is as follows: var name = "The Window"; var object = {name: "My Object", getNameFunc: function () {var cur = this; return function () {return cur. name ;}}}; alert (object. getNameFunc (); // = "My Object the code above assigns this of the parent function object to the cur variable, its nested function can access its attributes through the cur variable. The callback JavaScript closure example function outerFun () {Var a = 0; function innerFun () {a ++; alert (a) ;}} innerFun (); // => the error code is incorrect. the scope of innerFun () is within outerFun (). It is wrong to call it outside outerFun. change it to the following: Closure: Js Code function outerFun () {var a = 0; function innerFun () {a ++; alert (a) ;}return innerFun; // note here} var obj = outerFun (); obj (); // The result is 1obj (); // The result is 2var obj2 = outerFun (); obj2 (); // The result is 1obj2 (); // The result is 2. What is a closure? When an internal function is referenced outside of its scope, the closure of the internal function is created, if an internal function references a variable in an external function After the function is called, these variables will not be released in the memory, because the closure needs them. example: Js Code function outerFun () {var a = 0; alert (a);} var a = 4; outerFun (); // => 0 alert (a); // => 4, the result is 0, 4. because the var keyword is used in the function to maintain the scope of a within outFun. let's look at the following code: Js Code function outerFun () {// No var a = 0; alert (a);} var a = 4; outerFun (); /// => 0 alert (a); // => 0. The result 0 is really strange. Why?? The scope chain is the term used to describe a path. The variable value can be determined along this path. when a = 0 is executed, because the var keyword is not used, the value assignment operation will link to var a = 4 along the scope and change its value.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.