这篇文章主要通过举例介绍了解决 js 函数闭包内存泄露问题的办法,感兴趣的小伙伴们可以参考一下
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
本文通过举例,由浅入深的讲解了解决 js 函数闭包内存泄露问题的办法,分享给大家供大家参考,具体内容如下
原始代码:
- 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()())
优化后的代码:
- 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()())
稍微复杂一点的例子:
- 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。
这里存在内存泄露问题,优化后的代码如下:
- 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()()());
来源: http://www.phperz.com/article/17/0217/267422.html