面试的时候经常碰到关于闭包的问题

 
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()())

相关文章:

  • 2022-12-23
  • 2021-09-30
  • 2021-11-23
猜你喜欢
  • 2022-12-23
  • 2018-12-04
  • 2021-04-30
  • 2021-10-20
  • 2022-01-03
  • 2021-10-17
相关资源
相似解决方案