1

我正在为移动设备构建一些东西,并希望以某种方式清除空对象、变量以释放一些内存。在这里,我有两个简单的示例,我相信它们都是匿名函数,但是哪种方法更好或更有效?对不起,如果我弄错了。对我来说,两者似乎都在做同样的事情,尽管我更喜欢第一个,因为在我需要它之前不会创建对象。第二个版本将立即执行用于创建变量、对象等的代码,但在我需要它之前不会执行主构建功能。

我只是想弄清楚哪种方式更常见。我知道像我这样的初学者大多误解了匿名函数的使用。

V1

var app = function() {

        //create variables, objects
        var a = 'Data 1';
        var b = 'Data 2';

        //do some things    
        console.log(a + ', ' + b);

        //do a cleanup
        app.cleanup = function() {

            a = null;
            b = null;
            console.log(a, b);

        }
    }
    setTimeout(app, 200);

V2

var app = {};

    (function(){

        //create variables, objects
        var a = 'Data 1';
        var b = 'Data 2';

        app.build = function(){                 

            //do some things
            console.log(a + ', ' + b);          

        }

        //do a cleanup
        app.cleanup = function(){

            a = null;
            b = null;
            console.log(a, b);

        }   

        setTimeout(app.build,200);

    })();

稍后在 html 或事件中

<input type="button" onclick="app.cleanup()" value="clean" />
4

1 回答 1

2

You shouldn't be worrying about freeing up resources. JavaScript has a garbage collector which will pick up variables which fall out of scope and destroy them. Delete a reference to an object when you don't need it using delete obj.yourReference, reference = null or something similar, and let the garbage collector do the rest.

You'll find that #1 will automatically reclaim the a and b variables itself automatically, if you remove your app.cleanup() definition. Unless you do that, a and b are both enclosed in the closure created by the cleanup function you're leaving behind, so you're stopping the garbage collector from doing it's thing.

To get rid of the whole app in #1, you'll have to do delete window.app or app = null as window holds a reference to it.

于 2011-11-29T12:15:22.927 回答