浅谈JavaScript匿名函数与闭包

一、 匿名函数
 
//普通函数定义:
//单独的匿名函数是无法运行的。就算运行了,也无法调用,因为没有名称。
如: function(){
            alert(‘123’);
        }                        //语法错误,无法执行
 
1.简单的使用:
    var box =  function(){
        return ‘Lee’;
    }
    alert (box());        //需要调用box()方法。
 
2.通过自我执行来执行匿名函数
    (function(){                //语法格式:(匿名函数)();   第一个圆括号放匿名函数,第二个圆括号执行
        alert(‘123')
    })();
 
//把匿名函数自我执行的返回值赋给变量
    var box =  (function(){       
          return 200;
       })();
    alert(box);                //参考以上1,直接调用box变量。
 
3.通过自我执行匿名函数传参
    (function(age){
        alert(age);
    })();
 
4.函数里面放一个匿名函数
    function box () {
         return function () {
             return 'pjh';
         }
     }
     alert(box()());
     //另外一种调用方法(更加方便):
     var b = box();
     alert(b());
 

 
二、闭包
    闭包是指有权访问另一个函数作用域中的变量的函数,创建闭包的常用方式,就是在一个函数内创建另一个函数,通过另一个函数访问这个函数的局部变量。
 
    使用闭包有一个优点,也是它的缺点;就是把局部变量驻留在内存中,可以避免使用全局变量。(全局变量污染导致应用程序不可预测性,每个模块都可以调用必定引来灾难!所以推荐使用私有的,封装的局部变量)。
 
  1. 使用匿名函数实现局部变量驻留内存从而累加。
        function box () {
            var age = 100;
            return function(){
               age++;
               return age;
            }
        }
        var b = box();
        alert(b());
        alert(b());
        alert(b());
        b = null;      //解除引用,等待垃圾回收
        alert(b);        //程序将报错,因为b已经销毁不存在了!
 
PS:由于闭包里作用域返回的局部变量资源不会被立即销毁回收,所以可能会占用更多的内存。过度使用闭包会导致性能下降,建议在非常有必要的情况下才使用闭包。
 
  1. 通过闭包的自我执行来实现数组的遍历打印
        function box () {
            var arr = [];
            for (var i=0;i<5;i++) {
                arr[i] = (function (num) {
                     return function () {        
                          return num;
                     }
                  })(i);
            }
            return arr;
        }
        var b = box();
        for (var i=0; i<5; i++) {
            alert(b[i]());
        }
 
  1. 关于this对象
    var box = {
        getThis:function () {
            return function () {
                return this;
            }
        }
     };
    alert(box.getThis()());        //返回 object Window
 
PS:正常情况下,this在全局环境中就是指的window,如果在对象内部就是指向这个对象。而闭包却在运行时指向window(因为闭包并不属于这个对象的属性或者方法)。       
 
   例子:
    var user = "this window";
 
    var box = {
        user:'this box',
        getThis:function () {
            return function () {
            return this.user;
            }
        }
    };
 
    alert(box.getThis()());    //this window
    alert(box.getThis().call(box));    //this box
 
ps: alert(box.getThis().call(box)); 中的call(box)的作用是对象冒充。
 
    改进:
    var box = {
        user:'this box',
        getThis:function () {    //这里作用域的this是box
            var that = this;
            return function () {    //这里作用域的this是window
                return that.user;
            }
        }
    };
 
    alert(box.getThis()());    //this window
 
  1. 内存泄露问题
 
   IE浏览器中无法销毁驻留在内存中的元素,需要关闭浏览器后才进行销毁,所以存在内存泄露的问题,需要自己编写代码时手动清除。
 
    function box(){
        var Div = document.getElementById(“HTML页面的某个id”)
        var text = Div.innerHTML;
        Div.onClick = function(){
            alert(text);
        };
        Div = null        //手动接触引用
    }

注意:
    JavaScript 的声明没有块级作用域
例如:
    function box(){
        for (var index = 0; index < 5; index++) {        //创建index对象
            var j = index;
        }
    alert(i);            //输出Index的值。
    }
 
PS:因为JavaScript没有块级作用域,因此创建的局部变量不会自动销毁。