面试的时候经常碰到关于闭包的问题
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
},
getName:function(){
alert(this.name);
}
};
alert(object.getNameFunc()()); //The Window
object.getName(); //My Object
解决js函数闭包内存泄露问题的办法
function Cars(){
this.name = "Benz";
this.color = ["white","black"];}
Cars.prototype.sayColor=function(){
var outer=this.color;//保存一个副本到变量中
return function(){
return outer//应用这个副本
}
outer=null;//释放内存
}
var instance=new Cars();
console.log(instance.sayColor()())