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