闭包: 一个函数能够读取另外一个函数里面的变量。
闭包的作用: <1>读取函数内部的变量;<2>让这个变量的值始终保持在内存中,不会在父函数调用后被自动清除。
使用闭包注意事项:由于闭包会使得函数中的变量都被保存在内存中,内存消耗很大,所以不能滥用闭包,否则会造成网页的性能问题,在IE中可能导致内存泄漏,解决办法是在退出函数之前,将不使用的局部变量全部删除。
解决闭包内存泄漏的办法:
本文通过举例,由浅入深的讲解了解决js函数闭包内存泄露问题的办法,分享给大家供大家参考,具体内容如下 (http://www.jb51.net/article/78597.htm)
原始代码:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 function Cars(){ this .name = "Benz" ; this .color = [ "white" , "black" ]; } Cars.prototype.sayColor = function (){ var outer = this ; return function (){ return outer.color }; }; var instance = new Cars(); console.log(instance.sayColor()())优化后的代码:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 function Cars(){ this .name = "Benz" ; this .color = [ "white" , "black" ]; } Cars.prototype.sayColor = function (){ var outerColor = this .color; //保存一个副本到变量中 return function (){ return outerColor; //应用这个副本 }; outColor = null ; //释放内存 }; var instance = new Cars(); console.log(instance.sayColor()())稍微复杂一点的例子:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 function inheritPrototype(subType,superType){ var prototype = Object(superType.prototype); prototype.constructor = subType; subType.prototype = prototype; } function Cars(){ this .name = "Benz" ; this .color = [ "white" , "black" ]; } Cars.prototype.sayColor = function (){ var outer = this ; return function (){ return outer.color; }; }; function Car(){ Cars.call( this ); this .number = [321,32]; } inheritPrototype(Car,Cars); Car.prototype.sayNumber = function (){ var outer = this ; return function (){ return function (){ return outer.number[outer.number.length - 1]; } }; }; var instance = new Car(); console.log(instance.sayNumber()()());首先,该例子组合使用了构造函数模式和原型模式创建Cars 对象,并用了寄生组合式继承模式来创建Car 对象并从Cars 对象获得属性和方法的继承;
其次,建立一个名为instance 的Car 对象的实例;instance 实例包含了sayColor 和sayNumber 两种方法;
最后,两种方法中,前者使用了一个闭包,后者使用了两个闭包,并对其this 进行修改使其能够访问到this.color 和this.number。
这里存在内存泄露问题,优化后的代码如下:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 function inheritPrototype(subType,superType){ var prototype = Object(superType.prototype); prototype.constructor = subType; subType.prototype = prototype; } function Cars(){ this .name = "Benz" ; this .color = [ "white" , "black" ]; } Cars.prototype.sayColor = function (){ var outerColor = this .color; //这里 return function (){ return outerColor; //这里 }; this = null ; //这里 }; function Car(){ Cars.call( this ); this .number = [321,32]; } inheritPrototype(Car,Cars); Car.prototype.sayNumber = function (){ var outerNumber = this .number; //这里 return function (){ return function (){ return outerNumber[outerNumber.length - 1]; //这里 } }; this = null ; //这里 }; var instance = new Car(); console.log(instance.sayNumber()()());以上就是为大家分享的解决方法,希望对大家的学习有所帮助。
