首页 >web前端 >js教程 >关于闭包问题的详细介绍

关于闭包问题的详细介绍

零下一度
零下一度原创
2017-06-26 10:52:271472浏览

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

 
<span style="font-size: 15px; font-family: 宋体"><code class="lang-javascript"><span class="hljs-keyword">var name = <span class="hljs-string">"The Window";   
<span class="hljs-keyword">var object = {
    name : <span class="hljs-string">"My Object",   
    getNameFunc : <span class="hljs-function"><span class="hljs-keyword">function<span class="hljs-params">(){   <span class="hljs-keyword">return <span class="hljs-function"><span class="hljs-keyword">function<span class="hljs-params">(){   <span class="hljs-keyword">return <span class="hljs-keyword">this.name;   
        };   
    },

    getName:<span class="hljs-function"><span class="hljs-keyword">function<span class="hljs-params">(){
        alert(<span class="hljs-keyword">this.name);
    }   
};   
alert(object.getNameFunc()());  <span class="hljs-comment">//The Window
object.getName();  <span class="hljs-comment">//My Object<br/></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></span>

 

解决js函数闭包内存泄露问题的办法

function Cars(){
  this.name = "Benz";
  this.color = ["white","black"];
}
Cars.prototype.sayColor = function(){
  var outer = this.color; //保存一个副本到变量中
<span style="font-size: 15px"> return function(){ </span><br/><span style="font-size: 15px">return outer//应用这个副本</span>
};
outer = null; //释放内存
<span style="font-size: 15px">};<br/> var instance = new Cars(); <br/>console.log(instance.sayColor()())</span>

 

以上是关于闭包问题的详细介绍的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn