javascript匿名函数垃圾回收 [英] javascript anonymous function garbage collection

查看:154
本文介绍了javascript匿名函数垃圾回收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的功能

function do(callback) {
  //do stuff
  callback();
}

然后我传入一个匿名函数:

and then I pass in an anonymous function:

do(function() { //do something else });

在网页的生命周期内是否收集了匿名函数?如果没有,我怎么能让它可用于GC?

does that anonymous function ever get collected during the lifespan of the page? If not, how can i make it available for GC?

我必须这样做吗?

var h = function() { //do something };
do(h);
delete h;

我是否还要担心这个?我正在构建一个具有较长生命周期的Web应用程序,使得许多ajax调用保持对象一段时间并且实际上并不需要页面刷新来导航。所以我想弄清楚我是否会陷入内存泄漏怪物。

Do I even have to worry about this? I am building a web app that has a long lifespan, makes a lot of ajax calls keeps objects for a while and doesn't really require a page refresh to navigate thru. So I'm trying to figure out if I might fall into a memory leak monster.

推荐答案

对匿名函数的唯一引用是函数参数,并且在函数完成时消失,因此您的回调将在此之后用于垃圾回收。除非其他东西得到它的引用,这可以通过闭包轻松实现:

The only reference to the anonymous function is the function argument, and that disappears when the function finishes, so your callback will be available for garbage collection after that. Except when something else gets a reference to it, which can happen easily with closures:

function doo(callback) {
    $.get(url, function() {
        // callback is visible here!
    });
    callback();
}
doo(function() { /* do something else */ });

回调(以及创建的整个范围)通过调用 doo )必须保留在内存中,因为内部函数可以通过闭包引用它;它只能在内部函数被垃圾收集时被垃圾收集,并且由于该函数是jqXHR对象的一个​​属性,该对象必须在此之前进行垃圾收集,谁知道何时会发生...

callback (along with the whole scope created by calling doo) must stay in the memory, because the inner function can reference it through the closure; it can only be garbage collected when the inner function is garbage collected, and since that function is a property of the jqXHR object, that object must be garbage collected before that, and who knows when that will happen...

更新您可以通过不在其他功能中定义功能来避免不必要的关闭:

Update You can avoid unnecessary closures by not defining your functions inside other functions:

var func = function() {
    // callback is not visible here
}
function doo(callback) {
    $.get(url, func);
    callback();
}
doo(function() { /* do something else */ });

这篇关于javascript匿名函数垃圾回收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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