Je rencontre souvent des questions sur les fermetures lors des entretiens
<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>
Solution au problème de fuite de mémoire de la méthode de fermeture des fonctions 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>
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!