Home > Web Front-end > JS Tutorial > Detailed introduction to closure issues

Detailed introduction to closure issues

零下一度
Release: 2017-06-26 10:52:27
Original
1468 people have browsed it

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>
Copy after login

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; //保存一个副本到变量中
Copy after login
<span style="font-size: 15px"> return function(){ </span><br/><span style="font-size: 15px">return outer//应用这个副本</span>
Copy after login
};
Copy after login
outer = null; //释放内存
Copy after login
<span style="font-size: 15px">};<br/> var instance = new Cars(); <br/>console.log(instance.sayColor()())</span>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template