Home  >  Article  >  Web Front-end  >  Detailed introduction to closure issues

Detailed introduction to closure issues

零下一度
零下一度Original
2017-06-26 10:52:271454browse

I often encounter questions about closures during interviews

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

How to solve the problem of js function closure memory leaks

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>

The above is the detailed content of Detailed introduction to closure issues. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn