A netizen asked a question, such as the next HTML, why each output is 5
- <html >
- <head>
- <Meta http-equiv= "content-type" content= "text/html; Charset=utf-8 " />
- <title> Closure demo </title>
- <style type="Text/css">
- </style>
- <script type="Text/javascript">
- function init () {
- var pary = document.getelementsbytagname ("P");
- for (var i=0; I<pary.length; i++) {
- Pary[i]. onclick = function () {
- alert (i);
- }
- }
- }
- </Script>
- </head>
- <body onload="init ();" >
- <P> Product one </P>
- <P> Product one </P>
- <P> Product one </P>
- <P> Product one </P>
- <P> Product one </P>
- </body>
- </html>
There are two ways to solve this problem.
1. Save the variable i to each paragraph object (p)
- function init () {
- var pary = document.getelementsbytagname ("P");
- For ( var i=0; i<pary.length; i++) {
- PARY[I].I = i;
- Pary[i].onclick = function () {
- Alert (this.i);
- }
- }
- }
2. Save the variable i in the anonymous function itself
- function Init2 () {
- var pary = document.getElementsByTagName ("P");
- For (var i=0; i<pary.length; i++) {
- (Pary[i].onclick = function () {
- alert (ARGUMENTS.CALLEE.I);
- }). i = i;
- }
- }
Add 3 more kinds
3, add a layer of closure, I in the form of function parameters passed to the inner layer function
- function Init3 () {
- var pary = document.getelementsbytagname ("P");
- For ( var i=0; i<pary.length; i++) {
- (function (ARG) {
- Pary[i].onclick = function () {
- Alert (ARG);
- };
- }) (i); //Call-time parameters
- }
- }
4, add a layer of closure, I in the form of local variables passed to the memory function
- function Init4 () {
- var pary = document.getelementsbytagname ("P");
- For ( var i=0; i<pary.length; i++) {
- (function () {
- var temp = i; //local variables at call time
- Pary[i].onclick = function () {
- Alert (temp);
- }
- })();
- }
- }
5, add a layer of closures, return a function as a response event (note the subtle difference from 3)
- function Init5 () {
- var pary = document.getelementsbytagname ("P");
- For ( var i=0; i<pary.length; i++) {
- Pary[i].onclick = function (ARG) {
- return function () {//Returns a functional
- Alert (ARG);
- }
- } (i);
- }
- }
There's another way.
6, with the function implementation, in fact, each generation of an instance of the functions will produce a closure
- function Init6 () {
- var pary = document.getelementsbytagname ("P");
- For ( var i=0; i<pary.length; i++) {
- Pary[i].onclick = New Function ("alert (" + i + ");"); //new One function instance at a time
- }
- }
from:http://zhouyrt.javaeye.com/blog/250073