1

I want to remove object itself by function of it from a object collection. If I code like below does it course to reference cycle or any other error.

const obj_collec={};

function Obj(id){
    this.id=id;
    this.remove=function(){
        delete obj_collec[this.id]
    }
}

obj_collec['obj1'] = new Obj('obj1');
console.log(obj_collec)

obj_collec['obj1'].remove();
console.log(obj_collec)

I know that I can do that same thing with delete obj_collec['obj1']. But I want to know that what happens if I code like above.

Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
Chamod
  • 587
  • 2
  • 6
  • 17
  • 1
    "*But I want to know that what happens if I code like above.*" nothing special. It just works. It's a slightly odd code to have but syntactically and functionally it's OK. It will just remove the object from `obj_collec` and make it eligible for garbage collection as normal. – VLAZ Sep 29 '20 at 11:05
  • @VLAZ doesn't it cause to reference cycle ? – Chamod Sep 29 '20 at 11:08
  • Why would it? You're calling `delete obj_collec['obj1']` and that's it. The object instance is still referenced while the method is executing but when the stack clears (after the method ends), there are no other references to that object any more. – VLAZ Sep 29 '20 at 11:09
  • @VLAZ Thank you for explaining that. I got that now. – Chamod Sep 29 '20 at 11:15
  • What kind of reference cycle would you expect, and what would the problem with that? Sure, without the `remove` method the `new Obj` wouldn't reference the `obj_collect` that it is part of but I don't see how that matters. – Bergi Sep 29 '20 at 12:58
  • @Bergi I had some misunderstand. Now I clear that. – Chamod Sep 29 '20 at 13:06

0 Answers0