A detailed explanation of JavaScript closure mechanism and _javascript techniques of instance Code

Source: Internet
Author: User
Tags anonymous closure

The first is to distinguish between two concepts, one is anonymous function , the other is closure .

The anonymous function is to create a function without a given function name. Often, including function expressions, you define an anonymous function, and then assign the function to a variable, which at this point is equivalent to the function's name of the function, for example:

var sayhi = function () {
  alert ("Hi");
};//Note This semicolon
sayhi ();//Call function

Another common use of anonymous functions is callback functions, such as those commonly used in JQuery:

$ ("P"). Click (function () {
  alert ("click");
});

In addition, an anonymous function is used as a return value for a function:

function Saynamewithage (age) {return
  function (person) {
    if (person.age = = age) {return
      person.name;
    }
  }
}

So what's the matter with closures? The so-called closure, in fact, is a function, and this function is a little more special, it has the right to access other function scope variables.

From the definition we found that in fact, in the above anonymous function example, there is such a closure. In the last example, the anonymous function accesses the parameter age of the function saynamewithage, and the anonymous function as the return value is a closure.

To fully understand the closure, you must understand the entire mechanism of the function call, which is explained from the relevant knowledge of the scope chain.

First look at the following example:

function Sayname (name) {
  alert (name);
}
Sayname ("Jack");

When the above function sayname is called, a corresponding execution environment and scope chain is created, as shown in the following figure:

When the Sayname function is called, the the corresponding scope chain is created, and the scope contains two references to two objects, one of which is a global variable object that was created when the function was created, and is copied into the scope chain only when the function is invoked And the other is the active object of the function, which is created when the function is called.

When you access a variable in a function, you search for a variable from the scope that corresponds to the name.

When the function is finished, the active object of the function is destroyed and the global variable object is kept in memory forever.

However, the above is the case of ordinary functions, for the closure is another case:

Take the Saynamewithage function above as an example:

function Saynamewithage (age) {return
  function (person) {
    if (person.age = = age) {return
      person.name;
    }
  }
//Create function
var sayname = Saynamewithage (a);
Call function
var name = Sayname ({name: "Jack", age:18});
Unbind a reference to an anonymous function
sayname = null;

When the above Sayname function is invoked, the resulting scope chain looks like this:

When the anonymous function is return, its scope chain is created and contains the active object and the global variable object of the external function, so that the anonymous function can access all the variables defined in the Saynamewithage function, that is, a closure.

Such closures will have a problem, that is, when the Saynamewithage function is completed (most of the garbage disposal mechanism of JS is marked clear), the active object is referenced by the closure, so the active object will not be destroyed, only when the anonymous function is destroyed, saynamewithage Object is destroyed, the last line above does not only attempt to destroy the object of the closure, but also to destroy the active object of the external function. So, careful use of closure!!!

With regard to closures, there is also a need to note that a variable that accesses other functions in a closure is actually a reference to the active object of the closure's scope chain, rather than the active object of the closure itself. Look at the following example:

function outer () {
  var result = new Array ();
  for (var i = 0; i < 5; i + +) {
    Result[i] = function () {return
      i;
    };
  }
  return result;
}

As expected, the value in each item of the array returned by the last outer should be consistent with its subscript. But the final result is that each item has a value of 5
It's not hard to imagine that in all of the closure's scope chains above, there is a reference to the parameter I in the active object of outer and to the same object.

When the outer function completes, the value of I is 5. That is, the value of accessing I in all closures is 5

So, we can do the desired effect in another way:

function outer () {
  var result = new Array ();
  for (var i = 0; I < 5 i + +) {
    Result[i] = (fuction (index) {return
      index;
    }) (i);
  }
  return result;
}

Here we define a parameter index for the anonymous function and call the function immediately in each loop, copying the current value of I to the parameter index (note that JS is passed by value) and assigning the returned index to result.

In addition, another problem that needs to be noted in closures is the this object.

The This object is bound in JS in a function-based execution environment when the function is run. The execution environment of an anonymous function is global, that is, in an anonymous function, the This object usually points to window.

var name = "Tom";
var person = {
  name: ' Jack ',
  sayname:function () {return
    (function () {return
      this.name;
    }) ();
  }
}
Person.sayname (); Tom

It accesses the this.name in the closure, where the This object is not the This object that obtains itself or person, but points to window.

If you need to access the This object of the external function in the closure, you can define a variable in the external function to pass the This object to the variable.

var name = "Tom";
var person = {
  name: ' Jack ',
  sayname:function () {
    var self = this;
    Return (function () {return
      self.name;
    }) ();
  }
}
Person.sayname (); Jack



Thank you for reading, I hope to help you, thank you for your support for this site!

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.