Better approach nulling variables, objects in Javascript

时光总嘲笑我的痴心妄想 提交于 2020-01-03 04:23:06

问题


I am building something for mobile and would like somehow to clear, null objects, variables to release a bit of memory. Here I have two quick examples, both are anonymous functions as I believe but what way is better or more valid approach? Sorry if I get it all wrong. To me both seem to do the same thing although I like more the first one as objects wont be created until I need it. The second version would immediately execute the code for creating variables, objects etc. but not doing the main build function until I need it.

I am just trying to figure out what way is more common. I know that beginners like me mostly misunderstand the use of anonymous functions.

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);

    })();

Later in html or event

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

回答1:


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.



来源:https://stackoverflow.com/questions/8310182/better-approach-nulling-variables-objects-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!