Deep understanding of the closure characteristics of JavaScript

Source: Internet
Author: User
Tags add closure return variable

A netizen asked a question, such as the next HTML, why click All the paragraph p output is 5, instead of alert out corresponding 0,1,2,3,4.

 
 
  1. <! DOCTYPE html>
  2. <meta charset= "Utf-8"/>
  3. <title> Closure Demo </title>
  4. <style type= "Text/css" >
  5. p {background:gold;}
  6. </style>
  7. <script type= "Text/javascript" >
  8. function init () {
  9. var pary = document.getElementsByTagName ("P");
  10. for (var i=0; i<pary.length; i++) {
  11. Pary[i].onclick = function () {
  12. alert (i);
  13. }
  14. }
  15. }
  16. </script>
  17. <body onload= "Init ();" >
  18. <p> Products 0</p>
  19. <p> Products 1</p>
  20. <p> Products 2</p>
  21. <p> Products 3</p>
  22. <p> Products 4</p>
  23. </body>

The above scenes are often encountered by beginners. Gets the collection of HTML elements to iterate over the element add event. Gets the corresponding index (event handler) in the incident response function. But each fetch is the index of the last loop.

The reason is that beginners do not understand the closure characteristics of JavaScript. Via Element.onclick=function () {alert (i);} method to add a click event to the element. Response functions function () {alert (i);} I is not the corresponding I (such as 0,1,2,3,4) in each loop, but the value of the last I after the loop is 5. Or the loop-time response function is not able to save the corresponding value I, but the last i++ value of 5.

Understand the cause and find out a lot of solutions (purely interest). First two kinds of thinking

1. Save the variable i on each paragraph object (p)

 
  
  
  1. function Init1 () {
  2. var pary = document.getElementsByTagName ("P");
  3. for (var i=0; i<pary.length; i++) {
  4. PARY[I].I = i;
  5. Pary[i].onclick = function () {
  6. alert (THIS.I);
  7. }
  8. }
  9. }

2. Save the variable i to the anonymous function itself

 
  
  
  1. function Init2 () {
  2. var pary = document.getElementsByTagName ("P");
  3. for (var i=0; i<pary.length; i++) {
  4. (Pary[i].onclick = function () {
  5. alert (ARGUMENTS.CALLEE.I);
  6. }). i = i;
  7. }
  8. }

And then I thought of three more.

3. Add a layer closure, I pass the function parameter form to the inner layer function

 
  
  
  1. function Init3 () {
  2. var pary = document.getElementsByTagName ("P");
  3. for (var i=0; i<pary.length; i++) {
  4. (function (ARG) {
  5. Pary[i].onclick = function () {
  6. Alert (ARG);
  7. };
  8. }) (i)//call time parameter
  9. }
  10. }

4, add a layer of closure, I in the form of local variables passed to the inner layer function

 
  
  
  1. function Init4 () {
  2. var pary = document.getElementsByTagName ("P");
  3. for (var i=0; i<pary.length; i++) {
  4. (function () {
  5. var temp = i;//local variable when called
  6. Pary[i].onclick = function () {
  7. Alert (temp);
  8. }
  9. })();
  10. }
  11. }

5, add a layer closure, return a function as a response event (note the subtle difference with 3)

 
  
  
  1. function Init5 () {
  2. var pary = document.getElementsByTagName ("P");
  3. for (var i=0; i<pary.length; i++) {
  4. Pary[i].onclick = function (ARG) {
  5. return function () {//returns a
  6. Alert (ARG);
  7. }
  8. } (i);
  9. }
  10. }

And then found two more

6, with function implementation, in fact, each generated a function instance will produce a closure

 
  
  
  1. function Init6 () {
  2. var pary = document.getElementsByTagName ("P");
  3. for (var i=0; i<pary.length; i++) {
  4. Pary[i].onclick = new Function ("alert (+ i +);"); /new a function instance at a time
  5. }
  6. }

7, with function implementation, pay attention to the difference with 6

 
  
  
  1. function Init7 () {
  2. var pary = document.getElementsByTagName ("P");
  3. for (var i=0; i<pary.length; i++) {
  4. Pary[i].onclick = Function (' Alert (' +i+ ') ');
  5. }
  6. }
"Responsible editor: Chen Yu new TEL: (010) 68476606"


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.