理解js中的闭包

使用闭包主要是为了设计私有的方法和变量。闭包的优点是可以避免全局变量的污染,缺点是闭包会常驻内存,会增大内存使用量,使用不当很容易造成内存泄露。在js中,函数即闭包,只有函数才会产生作用域的概念

闭包有三个特性

1.函数嵌套函数
2.函数内部可以引用外部的参数和变量
3.参数和变量不会被垃圾回收机制回收

闭包的面试题

var x = 20;
    var a = {
        x : 15,
        fn : function(){
            var x = 30;
            return function(){
                return this.x;
            };
        }
    };
    console.log(a.fn());     //function(){return this.x}
    console.log((a.fn())());   // 20
    console.log(a.fn()());     //20
    console.log(a.fn()() == (a.fn())());   // true
    console.log(a.fn().call(this));  // 20
    console.log(a.fn().call(a));    // 15

var color ='green';
var test={
  color:'blue';
  getColor:function(){
    var color = 'red';
    alert(this.color);
  }
}
var getColor = test.getColor;
getColor();   //green
tset.getColor();   //blue
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容