细节: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()()());
    原文作者:JS菌
    原文地址: https://segmentfault.com/a/1190000004050041
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞