[英]What is the best way to delete an object in JavaScript?
In JavaScript, I have complex objects comprising functions, variables and closures. 在JavaScript中,我有包含函数,变量和闭包的复杂对象。
These objects are very large, very complex and created and destroyed over and over again. 这些对象非常大,非常复杂,并且一遍又一遍地创建和销毁。 I will be working on a very low-powered, very low-memory device, so it's important to me that when the objects are deleted that they are really gone.
我将使用低功耗,低内存的设备进行工作,因此对我来说很重要的一点是,删除对象后它们实际上就消失了。
Here's a code example: 这是一个代码示例:
window["obj"] = {};
obj.fun1 = function(){
console.log(1);
};
(function(){
var n = 2;
function fun(){
console.log(n);
}
obj.fun2 = fun;
})();
(function(){
var w = "Three";
function fun(){
console.log(w);
}
obj.fun3 = fun;
})();
(function(){
var w = "f.o.u.r.";
function fun(){
setInterval(function(){
console.log(w);
}, 1e3); // e.g. a timeout
}
obj.fun4 = fun;
})();
obj.fun1();
obj.fun2();
obj.fun3();
obj.fun4();
var fun2 = obj.fun2;
// window.obj = null;
// window.obj = undefined;
delete window.obj;
console.log(typeof obj); // undefined
A secondary issue is the question of "lingering references", such as the following: 第二个问题是“参考余留”问题,例如:
fun2(); // 2
// Interval: "f.o.u.r.", "f.o.u.r.", "f.o.u.r.", "f.o.u.r." ...
Is there anything that can be done about those (except a manual clean up before deleting the object)? 有什么可以做的(除了删除对象之前的手动清理)?
A JSFiddle of the code above is here: http://jsfiddle.net/8nE2f/ 上面的代码的JSFiddle在这里: http : //jsfiddle.net/8nE2f/
You will have the best effect by doing this 这样您将获得最佳效果
window.obj = null;
delete window.obj;
Setting objects to null removes any references to it. 将对象设置为null将删除对其的所有引用。 Also remember that the delete command has no effect on regular variables, only properties.
还请记住,delete命令对常规变量无效,仅对属性有效。
To better ensure object destruction you may consider not using the global context at all, that is usually considered as an antipattern. 为了更好地确保对象销毁,您可以考虑根本不使用全局上下文,通常将其视为反模式。
The only way to get rid of an object is for JavaScript to garbage-collect it, so making sure there really aren't any references to the object left and praying is the only way to go. 摆脱对象的唯一方法是JavaScript对其进行垃圾回收,因此确保确实没有对对象的任何引用,并且祈祷是唯一的方法。
If you're repeatedly creating and destroying the same object, consider using an object pool . 如果要重复创建和销毁同一对象,请考虑使用对象池 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.