Javascript的闭包

闭包是什么?闭包是Closure,简而言之,闭包就是:


  • 闭包就是函数的局部变量集合,只是这些局部变量在函数返回后会继续存在。
  • 闭包就是就是函数的“堆栈”在函数返回后并不释放,我们也可以理解为这些函数堆栈并不在栈上分配而是在堆上分配
  • 当在一个函数内定义另外一个函数就会产生闭包 比如如下的代码:
function greeting(name) {     var text = 'Hello ' + name; // local variable     //     return function() { alert(text); } } var sayHello=greeting("Closure"); sayHello()  // 访text
 
    上述代码的执行结果是:Hello Closure,因为sayHello()函数在greeting函数执行完毕后,仍然可以访问到了定义在其之内的局部变量text。这个就是一个闭包的效果,闭包在Javascript中有多种应用场景和模式,比如Singleton,Power Constructor等这些Javascript模式都离不开对闭包的使用。
    • 因此闭包有如下3个特性:  
    • 1.函数嵌套函数
    • 2.函数内部可以引用外部的参数和变量
    • 3.参数和变量不会被垃圾回收机制回收,除非代码中把参数和变量或者外部函数强制为null.
    • 因为  javascript的垃圾回收原理
    • (1)在javascript中,如果一个对象不再被引用,那么这个对象就会被GC回收; 
    • (2)如果两个对象互相引用,而不再被第3者所引用,那么这两个互相引用的对象也会被回收。

    闭包的定义及其优缺点

    闭包  是指有权访问另一个函数作用域中的变量的函数,创建闭包的最常见的方式就是在一个函数内创建另一个函数,通过另一个函数访问这个函数的局部变量

    闭包的缺点就是常驻内存,会增大内存使用量,使用不当很容易造成内存泄露。
    比如如下代码:

     
    function assignHandler() {
        var el = document.getElementById('demo');
        el.onclick = function() {
            console.log(el.id);
        }
    }
    assignHandler();

      以上代码创建了作为el元素事件处理程序的闭包,而这个闭包又创建了一个循环引用,只要匿名函数存在,el的引用数至少为1,因些它所占用的内存就永完不会被回收。
    良好的写作习惯为:
     
     
    function assignHandler() {
        var el = document.getElementById('demo');
        var id=el.id;
        el.onclick = function() {
            
            console.log(id);
        }
        el=null;
    }
    assignHandler();

     

    闭包是 javascript 语言的一大特点,主要应用闭包场合主要是为了:设计私有的方法和变量。

    一般函数执行完毕后,局部活动对象就被销毁,内存中仅仅保存全局作用域



    下面附加几个闭包的样例:

      例子1:闭包中局部变量是引用而非拷贝  
     
    function say() {
        // Local variable that ends up within closure
        var num = 666;
        var sayAlert = function() { alert(num); }
        num++;
        return sayAlert;
    }
     
    var sayAlert = say();
    sayAlert()

     
    因此执行结果应该弹出的667而非666  。因为对闭包中alert(num)中的num而言是一个引用,下面的num++之后就变成了667;

    例子2:多个函数绑定同一个闭包,因为他们定义在同一个函数内。
     
     
    function setupSomeGlobals() {
        // Local variable that ends up within closure
        var num = 666;
        // Store some references to functions as global variables
        gAlertNumber = function() { alert(num); }
        gIncreaseNumber = function() { num++; }
        gSetNumber = function(x) { num = x; }
    }
    setupSomeGlobals(); // 为三个全局变量赋值
    gAlertNumber(); //666
    gIncreaseNumber();
    gAlertNumber(); // 667
    gSetNumber(12);//
    gAlertNumber();//12

     
    例子3:当在一个循环中赋值函数时,这些函数将绑定同样的闭包
     
    function buildList(list) {
        var result = [];
        for (var i = 0; i < list.length; i++) {
            var item = 'item' + list[i];
            result.push( function() {alert(item + ' ' + list[i])} );
        }
        return result;
    }
     
    function testList() {
        var fnlist = buildList([1,2,3]);
        // using j only to help prevent confusion - could use i
        for (var j = 0; j < fnlist.length; j++) {
            fnlist[j]();
        }
    }

      testList的执行结果是弹出item3 undefined窗口三次,因为这三个函数绑定了同一个闭包,而且item的值为最后计算的结果,但是当i跳出循环时i值为4,所以list[4]的结果为undefined.
      例子4:外部函数所有局部变量都在闭包内,即使这个变量声明在内部函数定义之后。
     
    function sayAlice() {
        var sayAlert = function() { alert(alice); }
        // Local variable that ends up within closure
        var alice = 'Hello Alice';
        return sayAlert;
    }
    var helloAlice=sayAlice();
    helloAlice();

      执行结果是弹出”Hello Alice”的窗口。即使局部变量声明在函数sayAlert之后,局部变量仍然可以被访问到。
     
    例子5:每次函数调用的时候创建一个新的闭包
     
    function newClosure(someNum, someRef) {
        // Local variables that end up within closure
        var num = someNum;
        var anArray = [1,2,3];
        var ref = someRef;
        return function(x) {
            num += x;
            anArray.push(num);
            alert('num: ' + num +
            '\nanArray ' + anArray.toString() +
            '\nref.someVar ' + ref.someVar);
        }
    }
    closure1=newClosure(40,{someVar:'closure 1'});
    closure2=newClosure(1000,{someVar:'closure 2'});
     
    closure1(5); // num:45 anArray[1,2,3,45] ref:'someVar closure1'
    closure2(-10);// num:990 anArray[1,2,3,990] ref:'someVar closure2'

     
     例子6:闭包中的this
      在 ECMAScript 中,要掌握的最重要的概念之一是关键字 this 的用法,它用在对象的方法中。关键字 this 总是指向调用该方法的对象。
     
    var name = 'Jack';
    var o = {
        name : 'bingdian',
        getName : function() {
            return function() {
                return this.name;  //this指向调用该方法的对象
            };
        }
    }
    console.log(o.getName()()); o.getName()返回的是一个匿名函数,调用该匿名函数时this指向的是该匿名函数,因此输出的结果为Jack
     
    var name = 'Jack';
    var o = {
        name : 'bingdian',
        getName : function() {
            var self = this;  //此时this的指向的是o
            return function() {
                return self.name;
            };
        }
    }
    console.log(o.getName()()); 在o.getName()里面的this指向的是o。    //bingdian

    如果你在js中使用new的方式构造对象,举个例子:
     
    function MyObject(name, message) {
      this.name = name.toString();
      this.message = message.toString();
      this.getName = function() {
        return this.name;
      };
      this.getMessage = function() {
        return this.message;
      };
    }
     强烈建议不这么做,是因为你在页面每次new出一个MyObject的对象是,在内存中有多分getName或者getMesage 方法,这样创建的多了,对性能也不是很好,更加很容易造成内存泄露,叫良好的书写方法如下:
     
    function MyObject(name, message) {
      this.name = name.toString();
      this.message = message.toString();
    }
    MyObject.prototype.getName = function() {
      return this.name;
    };
    MyObject.prototype.getMessage = function() {
      return this.message;
    };
     
    或者如下方式
     
    function MyObject(name, message) {
        this.name = name.toString();
        this.message = message.toString();
    }
    (function() {
        this.getName = function() {
            return this.name;
        };
        this.getMessage = function() {
            return this.message;
        };
    }).call(MyObject.prototype);
     
     因为如上述两种方式,你在页面创建多个MyObject对象时,内存中只有一份getName和geMessage的方法,因为这两个方法时在原型连上创建的。



    参考网址如下:

    http://blog.csdn.net/jameswenblog/article/details/11787893
     

    http://wlog.cn/javascript/javascript-closures.html
     
    http://segmentfault.com/a/1190000000652891#articleHeader4

#前端工程师#
全部评论
很实用,是个难点
点赞 回复
分享
发布于 2015-09-30 17:57

相关推荐

7 33 评论
分享
牛客网
牛客企业服务