On the _javascript techniques of JavaScript closure function

Source: Internet
Author: User
Tags anonymous closure memory usage

In JavaScript, closures are probably a concept that many people don't understand, and even many people confuse closures with anonymous functions.

 a closure is a function that has access to a variable in another function scope. The first thing to understand is that closures are functions. because it requires access to variables that are in effect on another function, we tend to create another function within one function, and "another function" is a closure.

such as the comparison function mentioned earlier:

  function Createcomparisonfunction (PropertyName) {return
   function (object1,object2) {
    var value1=object1[ PropertyName];
    var value2=object2[propertyname];
    if (value1<value2) {return= "" -1;= ""}else= "" If "(value1=" ">value2) {return
     1;
    } else{return
     0;
    }
   ;
  }
</value2) {>

In this function, because the return function accesses the variable propertyname that contains the function (the external function), we consider the function to be a closed package. Even if the closure is returned and invoked elsewhere, it still has access to PropertyName and is able to access the PropertyName variable, Because the scope of the Createcomparisonfunction function is contained in the scoped chain of the internal function (closure) . Therefore, to thoroughly understand closure, you need to thoroughly understand what happens when a function is invoked and what the scope chain is about.

 when a function is called, an execution environment is created (when the function is invoked, it enters the function execution environment) and the corresponding scope chain (the scope chain changes dynamically as the execution environment varies). (for functions), the active object of the function is initialized with the values of arguments and other named parameters (each execution environment has a variable object, which becomes the active object for the function). for functions with closures, the active object of the external function is always second in the scope chain, and the external function's active object is always in the third position ... Up to the global execution environment as the endpoint of the scope chain.

The following is a simple example to understand the scope chain and the variable object and the active object, regardless of the closure.

 function Compare (value1,value2) {
 if (value1<value2) {
  return-1;
 } else if (value1>value2) {return
  1;
 } else{return
  0;
 }
<br> var result=compare (5,10);

The above code first defines the compare () function and then calls it in the global scope. When the compare function is called, first, a function execution environment is created, and each execution environment corresponds to this variable object, that is, the scope chain and function execution environment are created at the same time, where the front-end of the scope chain is the active object of the Compare function (in the function, the variable object is also called the active object). Arguments, value1, value2 are included in the Compare active object: Although the arguments array object contains value1 and value2, we would like to enumerate them separately, Rather than simply assume that only arguments are contained in compare active objects, because value1 and value2 are also included in the compare active object.

For the above code, the variable object of the global Execution Environment (once again: each execution environment has a corresponding variable object) contains result and compare, which is the second in the scope chain of the Compare () execution environment.

When we create the Compare () function, we create a scope chain that contains a global variable object, which is saved in the [[Scope] property within the Compare function, and when the compare function is invoked, an execution environment is created for the function, and then the function is copied by the The object in the [[scope]] property constructs the scope chain of the execution environment. As follows:

the nature of a scope chain is a list of pointers to variable objects that reference but do not actually contain variable objects. Whenever a variable is accessed in a function, a variable with the corresponding name is searched from the front-end of the scope chain along the scope chain. We know that the variables object of the global environment always exists, and the variable object of the local environment (such as the Compare () function execution Environment) exists only when the function executes, and once executed, the local variable object (the active object) is destroyed. But in closures, this is different.

The code that starts the blog post is copied as follows:

 function Createcomparisonfunction (PropertyName) {return
 function (object1,object2) {
  var value1=object1[ PropertyName];
  var value2=object2[propertyname];
  if (value1<value2) {
   return-1;
  } else if (value1>value2) {return
   1;
  } else{return
   0;
  }
 ;
}

Because a function defined inside a function adds the active object containing the function (that is, the external function) to its scope chain. Therefore, the scope of the anonymous function defined inside the Createcomparisonfunction function actually contains the active object of the external function. If we execute the following code:

var compare=createcomparisonfunction ("name");
var result=compare ({name: "ZZW"},{name: "HT"});

At this point the scope chain of the anonymous function refers to the active object of the external function. Since an anonymous function is returned from an external function, its scope chain is initialized to the active object and the global variable object that contains the external function. This allows anonymous functions to access all the variables defined in the external function. More importantly, even if the external function is finished, its active object will not be destroyed because the scope chain of the anonymous function still references the active object. In other words, when the Createcomparison () function returns, the scope chain of its execution environment is destroyed, but her active object is still stored in memory. When the Numin function is destroyed, the active object of the external function is destroyed.

Because the closure carrier contains the scope of his function, the other functions are evaded to occupy more memory. Excessive use of closures may result in excessive memory usage, and we recommend that closures be considered only when absolutely necessary.

Impersonation block-level scopes

(function () {
 var now=new Date ();
 if (Now.getmonth () ==0&&now.getdate () ==1) {
  alert ("Happy New Year");
 }
) ();

This is modeled as a block-level scope, that is, an anonymous function is defined and called immediately.

The following is a demonstration of its role:

function Outputnumbers (count) {
 (function () {for
  (var i=0;i<count;i++) {
   console.log (i)
  }
 }) ();
 Console.log (i);
}
Outputnumbers (5);

This is caused by console.log (i) outside the block-level scope, because I is not defined. Note After the impersonation block-level scope is executed, the internal variables are destroyed.

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, if there are questions you can message exchange, but also hope that a lot of support cloud Habitat community!

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.