Javascript closure details, javascript details

Source: Internet
Author: User

Javascript closure details, javascript details

I have read the concepts and articles about closures on the Internet. Let's take a look at this issue.

Q: What is a closure?
A: In JavaScript, internal functions can always access the parameters and variables declared in their external functions, even after their external functions are returned (end of life.

This is the first time I encountered a closure problem.

<! Doctype html> 

If you have never used this before, you may think that clicking a paragraph will bring up the corresponding numbers 0, 1, 2, 3, 4 of this paragraph. But in fact it is always pop-up 5;

There have been a lot of blogs discussing this issue on the Internet, and they have provided a lot of methods to bring up the corresponding numbers.

Solution 1: Save variable I on an attribute of the corresponding section.

var pAry = document.getElementsByTagName("p"); for( var i=0; i< 5; i++ ) { pAry[i].no = i; pAry[i].onclick = function() { alert(this.no); } };

Solution 2: Add a closure, and I will pass it to the inner function as a function parameter.

var pAry = document.getElementsByTagName("p"); for( var i=0; i< 5; i++ ) { pAry[i].no = i; pAry[i].onclick = function() { alert(this.no); } };

For this closure problem, the online saying is "variable I is saved in the function as a pointer or variable address"; well, it is related to the pointer .... Then let's explore it.

Exploration 1, returns 10 instead

(Function test () {var temp = 10; for (var I = 0; I <5; I ++) {document. getElementById ("p" + I ). onclick = function () {alert (temp); // access the parent function's variable temp, closure }}; temp = 20 ;})();

Explore 2, return 10 at a time, and then return 20

(Function test () {var temp = 10; for (var I = 0; I <5; I ++) {document. getElementById ("p" + I ). onclick = function () {alert (temp); // The variable I, closure} if (I = 1) {alert (temp );}}; temp = 20 ;})();

From 1 and 2 of the exploration, we can draw a conclusion: the function accesses the variable at the same level as the function, then the variable is resident memory. Accessing this variable is essentially the address of the variable;

Next, I read an article about "this object in JS closures" and continue to discuss this.

// Js closure this object 1var name = 'The window'; var Object = {name: 'My object', getNameFunc1: function () {// return this. name; console. log (this); // object return function () {// closure. The global variable is accessed. this indicates the windows console. log (this); // windows return this. name; // The Window }}, getNameFunc2: function () {return this. name; // Access object}, aa: function () {alert (22) ;}}; alert (object. getNameFunc1 (); // The Window is displayed"

Q: Why didn't an anonymous function obtain the this object with its contained scope?
A: each function automatically obtains two special variables when called: this and arguments. When an internal function searches for these two variables, the command searches until its activity object, so it is never possible to directly access these two variables in the external function.
However, the following code can be used to achieve this (directly access the variables in external functions ):

// Js closure this object 2var name = 'window'; var Object = {name: 'My object', getNameFunc: function () {var that = this; console. log (this); // The output is the object return function () {console. log (this); // The output is still Windows return that. name ;}}}; alert (object. getNameFunc (); // The "My Object" dialog box is displayed"

The difference is that this object is assigned to a variable that, even after the function returns, that still references this object, so the object will be returned.
After writing so many closures, let's also say that closures are useful. Otherwise, it's really a bad guy to make a mess.

Here is an example of a typical closure:

Function A () {var a = 1; function B () {return a ;}; return B ;}; var C = (); // C obtain the access interface console of sub-scope B of. log (C (); // 1 C can access variable a in the parent scope of B

As long as the access interfaces of other scopes can be obtained from sub-scopes, other scopes have methods to access the variables of the parent-level scopes of the sub-scopes. In this way, it will be very useful if you need to access a function in the future.

Many of the above Code is actually found on the Internet. I just understood it and summarized the process.

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.