JavaScript的内存泄漏解释 [英] JavaScript memory leak explanation

查看:140
本文介绍了JavaScript的内存泄漏解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function addHandler() {  
    var el = document.getElementById('el');  
    el.onclick = function() {  
        this.style.backgroundColor = 'red';  
    }  
}

在code以上被列入一个 JavaScript的,并指出上述code会导致内存泄漏。

The code above was included in a Mozilla blog post on JavaScript and states that the above code causes a memory leak.

有人能解释超过:

由于厄尔尼诺参考无意中陷入了匿名内部函数创建的闭包。这将创建一个JavaScript对象(函数)和本地对象(EL)之间的循环引用。

Because the reference to el is inadvertently caught in the closure created for the anonymous inner function. This creates a circular reference between a JavaScript object (the function) and a native object (el).

谢谢!

推荐答案

@ thg435:它看起来像这可能是使用eval的结果。

@thg435: It looks like that might be a result of using eval.

执行在Firefox或Chrome以下与的手表,而在调试破报告为未定义Foo的价值

Executing the following in Firefox or Chrome with a watch on foo while breaking at debugger reports foo's value as undefined.

(function () {
  var foo = "bar";
  return function() {
    debugger;
  };
})()();

在执行了以下报告Foo的值,而在打破调试器

(function () {
  var foo = "bar";
  return function(_var) {
    debugger;
    return eval(_var);
  };
})()('foo');

这将是巨大拿到这个一个明确的答案。

It would be great to get a definitive answer on this.

这篇关于JavaScript的内存泄漏解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆