简体   繁体   English

从对象中删除对象?

[英]Delete object from object?

Given something like this: 给定这样的东西:

function test(){
   var o = {
      // ...
      del: function(){}
   }
   return o;
}

Is it possible to have .del() remove/set to null the reference to the variable o such that it becomes eligible for garbage collection? 是否可以将.del()删除/设置为对变量o的引用设置为null,以使其有资格进行垃圾回收?

In other words, is this possible (and if so how): 换句话说,这是否可行(如果可以的话):

var test1 = test();
// test1 = {...}
test1.del();
// test1 == null or test1 == undefined;

I did try setting o = null but the outside reference ( test1 would still refer to the object). 我确实尝试设置o = null但外部引用( test1仍将引用该对象)。 I also understand that setting test1 = null would solve the issue, but where's the fun in that? 我也知道设置test1 = null可以解决问题,但是这样做的乐趣何在?

Based on what I see in the comments, this pattern wouldn't do what you need. 根据我在评论中看到的内容,此模式无法满足您的需求。 You are returning a new instance of an object every time the test function is called or "newed" up. 每次调用或“更新”测试功能时,您都将返回对象的新实例。 It is up to the caller of the function to clean up it's new instance of "o". 由函数的调用者来清理它的新实例“ o”。 On this train of thought, you shouldn't have to explicitly set a value to null or undefined to make it eligible for garbage collection. 按照这种思路,您不必将值显式设置为null或undefined即可使其适合垃圾收集。 Once there are no more references to an object, it will be cleaned up for you. 一旦不再有对对象的引用,它将为您清除。

Here is a great example from MDN- 这是MDN的一个很好的例子-

function f(){
  var o = {};
  var o2 = {};
  o.a = o2; // o references o2
  o2.a = o; // o2 references o

  return "azerty";
}

f();

The internal scope of f() will be cleaned up after the function returns, since the variables inside are not "reachable" anymore. 函数返回后,将清理f()的内部范围,因为其中的变量不再“可访问”。 It's called the Mark and Sweep algorithm. 这称为标记和扫描算法。

No it would not be possible to have a method del() that would let an object be garbage collected. 不,不可能有一种方法del()可以让对象被垃圾回收。 For the garbage collector to kick in, the object must be unreachable, as you had in your post test1 = null; 为了启动垃圾收集器,对象必须不可访问,就像您在post test1 = null;

The purpose of garbage collection is so you don't have to worry about managing your memory. 垃圾收集的目的是让您不必担心管理内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM