Rumah > Artikel > hujung hadapan web > 关于闭包问题的详细介绍
面试的时候经常碰到关于闭包的问题
<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>
Atas ialah kandungan terperinci 关于闭包问题的详细介绍. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!