Javascript Closure (Closure) _ javascript skills

Source: Internet
Author: User
Closure is a difficult and characteristic of Javascript language. many advanced applications rely on closures for implementation. The following are my study notes, which are useful for beginners of Javascript.

I. Scope of variables

To understand closures, you must first understand the special variable scopes of Javascript.

Variables have two scopes: global variables and local variables.

The special feature of Javascript is that the function can directly read global variables.

var n=999;function f1(){  alert(n);}f1(); // 999

On the other hand, local variables in the function cannot be read outside the function.

function f1(){  var n=999;}alert(n); // error

Note that you must use the var command when declaring variables in a function. If you don't need it, you actually declare a global variable!

function f1(){  n=999;}f1();alert(n); // 999

2. how to read local variables from the outside?

For various reasons, we sometimes need to get local variables in the function. However, as we have already said, under normal circumstances, this cannot be done. it can only be implemented through a work und.

That is to define another function within the function.

function f1(){  var n=999;  function f2(){    alert(n); // 999  }}

In the code above, function f2 is included in function f1. all local variables in function f1 are visible to f2. But in turn, the local variables in f2 are invisible to f1. This is the unique "chain scope" structure (chain scope) of Javascript language. the sub-object will first look up the variables of all parent objects. Therefore, all variables of the parent object are visible to the child object, and vice versa.

Since f2 can read local variables in f1, as long as f2 is taken as the return value, we can't read its internal variables outside f1!

function f1(){  var n=999;  function f2(){    alert(n);   }  return f2;}var result=f1();result(); // 999

III. concepts of closures

The f2 function in the previous code is the closure.

Closure definitions in various professional documents are very abstract and hard to understand. In my understanding, closures are functions that can read internal variables of other functions.

In Javascript, only the subfunctions in a function can read local variables. Therefore, you can simply understand the closure as a function defined in a function ".

Therefore, in essence, closure is a bridge connecting the internal and external functions of a function.

IV. Use of closures

Closures can be used in many places. It has two major functions: one is to read the internal variables of the function mentioned above, and the other is to keep the values of these variables in the memory.

How can we understand this sentence? See the following code.

  function f1(){    var n=999;    nAdd=function(){n+=1}    function f2(){      alert(n);    }    return f2;  }  var result=f1();  result(); // 999  nAdd();  result(); // 1000

In this code, the result is actually the f2 function of the closure. It runs twice in total. The first value is 999, and the second value is 1000. This proves that the local variable n in function f1 has been stored in the memory and is not automatically cleared after f1 is called.

Why? The reason is that f1 is the parent function of f2, and f2 is assigned a global variable, which causes f2 to always be in the memory, while f2 depends on f1, therefore, f1 is always in the memory and will not be recycled by the garbage collection mechanism after the call is completed.

Another noteworthy part of this code is "nAdd = function () {n + = 1}". The var keyword is not used before nAdd, therefore, nAdd is a global variable rather than a local variable. Secondly, the value of nAdd is an anonymous function, and this anonymous function itself is also a closure, so nAdd is equivalent to a setter, you can operate the local variables inside the function outside the function.

5. Notes on using closures

1) because the closure will make the variables in the function be stored in the memory, the memory consumption is very large, so the closure cannot be abused, otherwise it will cause the performance of the web page, memory leakage may occur 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 value of the internal variable of the parent function.

VI. Questions

If you can understand the running results of the following two sections of code, you should understand the operating mechanism of the closure.

Code snippet 1

  var name = "The Window";  var object = {    name : "My Object",    getNameFunc : function(){      return function(){        return this.name;      };    }  };  alert(object.getNameFunc()());

Code snippet 2

  var name = "The Window";  var object = {    name : "My Object",    getNameFunc : function(){      var that = this;      return function(){        return that.name;      };    }  };  alert(object.getNameFunc()());   

The above is all the content of this article. I hope you will like it.

Related Article

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.