---
title: "再谈闭包,closure---javascript"
author: "xjw1987524"
date: "2010-12-14T22:49:09Z"
tags: []
categories: ["Web前端"]
slug: "closure-javascript"
draft: false
lastmod: "2010-12-14T22:49:51Z"
id: 842302
url: "https://fishlovefly.iteye.com/blog/842302"
---

再一次来谈谈javascript，发现现在网上大多数文章对于闭包的认识好像都是认为返回一个内部的函数这样一个标志才能认为是closure（闭包）。 也许有但是很是看到这样的文章能对javascript的闭包能有一个比较清晰地解释。下面我就来谈谈自己对javascript的闭包的看法，如有不对的地方欢迎大家批评一起学习。

              首先，谈谈一个常见的需求。

              有四个link，

           &lt;a href="#" class="mylink" id="0"&gt;1&lt;/a&gt;

          &lt;a href="#" class="mylink" id="1"&gt;2&lt;/a&gt;

          &lt;a href="#" class="mylink" id="2"&gt;3&lt;/a&gt;

         要求点击相应的链接弹出你点击的是第几个。

下面我给出几种实现方式

&lt;html&gt;

    &lt;head&gt;

        &lt;title&gt;sfsdf&lt;/title&gt;

        &lt;script language="JavaScript" type="text/javascript"&gt;

//第一种实现方式是将局部变量obj,和i传递给外部函数，这样就可以保留局部变量---这应该就是闭包的主要作用保留局部

//变量

            /\*function newInit(){

             for (var i = 1; i &lt;= 3; i++) {

             var obj = document.getElementById("a" + i);

             alertfunction(obj, i);

             }

             }

             function alertfunction(obj, i){

             obj.onclick = function(){

             alert(i);

             }

             }

             \*/

/*

    第二种跟下面的是一样的，只是这里是对所有的标签进行取得

            function newInit(){

var links=document.getElementsByTagName("a");

                for (var i = 0; i &lt; links.length; i++) {

var link=links\[i];

                   link.onclick=function()

{

var row=i;//row保留局部变量i

return function()

{

alert(row);//弹出

}

}();//立即执行

 

                    }

                }

            \*/

        function newInit(){            

            for (var i = 0; i &lt; 3; i++) {

                var link = document.getElementById(i);

                link.onclick = (function(){

                    var row = i;//保留变量

                    return function(){

                        alert(row);

                    }

                })();

 

 

            }

        }

        &lt;/script&gt;

    &lt;/head&gt;

    &lt;body onload="newInit()"&gt;

        &lt;a href="#" class="mylink" id="0"&gt;1&lt;/a&gt;

        &lt;a href="#" class="mylink" id="1"&gt;2&lt;/a&gt;

        &lt;a href="#" class="mylink" id="2"&gt;3&lt;/a&gt;

    &lt;/body&gt;

&lt;/html&gt;

 

 

另外附上一段英文，对javascript闭包的总结

 

- Whenever you use function inside another function, a closure is used.
- Whenever you use eval() inside a function, a closure is used. The text you eval can reference local variables of the function, and within eval you can even create new local variables by using eval('var foo = …
- When you use Function() inside a function, it does not create a closure. (The new function cannot reference the local variables of the function callingFunction()).
- A closure in JavaScript is like keeping a copy of the all the local variables, just as they were when a function exited.
- It is probably best to think that a closure is always created just on entry to a function, and the local variables are added to that closure.
- A new set of local variables is kept every time a function with a closure is called (Given that the function contains a function declaration inside it, and a reference to that inside function is either returned or an external reference is kept for it in some way).
- Two functions might look like they have the same source text, but have completely different behaviour because of their 'hidden' closure. I don't think JavaScript code can actually find out if a function reference has a closure or not.
- If you are trying to do any dynamic source code modifications ( for example: myFunction = Function(myFunction.toString().replace(/Hello/,'Hola')); ), it won't work if myFunction is a closure (Of course, you would never even think of doing source code string substitution at runtime, but...).
- It is possible to get function declarations within function declarations within functions - and you can get closures at more than one level.
- I think normally a closure is the term for both the function along with the variables that are captured. Note that I do not use that definition in this article!
- I suspect that closures in JavaScript differ from those normally found in functional languages.