JS Closed Package

Source: Internet
Author: User

Closures: The function of the closure is that when the parent scope finishes executing, you still have access to the scope of the Declaration and the function of the parent function, I have the following two understanding of the sentence

  1 closures are a function (a reference to a function object) that has a reference to the parent scope variable and function in its definition to cause the parent scope to continue to access the parent scope after execution

2 closures are a nested function function declaration that returns it to an external variable (itself a reference) so that a reference to the parent scope persists so that the parent scope is not recycled by the garbage collection mechanism to the appropriate function

 

 function    Test () {  var name = ' haha ';     function  sayname () {console.log (name);  } sayname (); } test ();//haha

The above example is a declaration of a nested function that defines a local variable (property) name inside the test (), and within it defines a function sayname () and references its property name

Invoking a function in JavaScript implicitly generates a call object, which is the active object, which contains its scope and the properties it accesses, and the access to the scope properties in the binding chain domain.

In the example above, call Test (), call Sayname () in test (), generate Sayname's active object, find the Name property of the parent scope along the scope of the action, sayname after execution, its active object is destroyed, and the active object of test is reached. Last object to destroy test

We can change a plan.

 

 function    Test () {  var name = ' haha ';     returnfunction  sayname () {console.log (name);  }}  var func = test (); Func ();//haha

When test () is executed, its name attribute should not be externally accessible (supposedly garbage collected), which is why?

Within test (), a function is defined (which can be understood as a property of test () , which has access to the parent scope property, and when we put the function (property) back to the external variable, there is an external access to the property of test (). Causes test () to not be garbage collected, so we can still guarantee access to the properties of test (), which is the basic principle of closures, and closures refer to the current test () Activity object

A closure is a special function that, when invoked, maintains the execution environment for the lookup of the variable name at that time, or it can be understood as a function with state (full solution of JavaScript programming)

A problem to be aware of

function  Test () {  var num = 1;   function  sayNum1 () {console.log (num);  } num+ +;   function  sayNum2 () {console.log (num); }  return  [saynum1,saynum2];} var func = test (); func[0] ();//2func[1] ();//2

In the above example, two functions are returned, they all refer to the active object of test to form a closure, the reason is to use this example because the value of NUM when declaring two functions is inconsistent but they end up referencing the test of the active object, so will return the same result, So I think of an embarrassing experience I went to the interview, in the <li><li> bound onclick event, click the corresponding list item is the actual display of the corresponding serial number, I did not write it, that is, all return a value, Put the right one down (it's OK to come back and consider the problem)

function    Test () {  var lis = document.getElementById (' container '). getElementsByTagName (' li ');  for (var i = 0;i < lis.length;i++function(j) {  return
   
    function
    () {Console.log (j); }            } (i);}       }

Here are some examples of how closures are used, as well as answers to another interview question

1) can be hidden through the closure of the information

The structure is such (function () () () () () ();

We call the anonymous function immediately, but the feature that makes the variable persist after the call is made using the closure

  

varobj = (function(){                 var position = {X:2,y:3};  function  sum_internal (A, a) {Console.log (number (a) + number (b)); }//position and Sum_internal (A, B) are equivalent to private variables and functions (attributes) return{sum:function(A, B) {returnSum_internal (A, b);}, x:position.x, Y:POSITION.Y};            })(); Obj.sum (1,5);//6 Console.log (obj.x);//2

The above example implements the hiding of information in the form of a return literal.

Using the method above, closures can be combined with classes to achieve access control

function person (name) {this.name = Name;this.sayname = function () {console.log (this.name);}} var person1 = new person (' haha ');p erson1.sayname ();

The above is a simple class definition, and in my other blog This example is illustrated by the prototype inheritance JavaScript

We can write the above definition into the following form, combining closures

function Person (name) {                returnfunction() {console.log (name);}};            }             var obj = person (' haha ');            Obj.sayname ();

Closures and callback functions

We can register closures as callback functions and avoid the problem of this reference

JS Closed Package

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.