Trace
Trace

Reputation: 18899

Set current object to null

How do I set the current object to null?

function ZPNode(){}; //Constructor 
function _destroy(){ 
    //this = null; --> Won't work obviously 
} 
ZPNode.prototype.remove = function(){ 
    //Remove node 
    _destroy.call(this); 
}; 

Edit: perhaps the description was not clear. What should happen is something like:

var tree = ZPTree.create(jsonArr);  
var node = tree.findNode(1); 
node.remove(); 
console.log(node); //null 

The reason why is simple. You don't want to accidentally do something like:

node.remove(); 
node.appendChild(anotherNode); //Oops 

Possible solution is to work with state on the object if there is no other way.

Edit2: After more research, I don't think that it is possible overall. I'll reluctantly go with a workaround solution. I can do something like:

tree.removeNode(node); 

Although it llooks less clean in my opinion.

Upvotes: 0

Views: 400

Answers (2)

Trace
Trace

Reputation: 18899

Ultimately I found the most logical solution for my specific use case.
It was as simple as to set the reference to the current tree to 0.

this._treeId = 0; 

It doesn't actually matter that the node continues to exist, since it wasn't connected to the tree anymore.
Even more, it would make sense to keep the node in existence, as it may be re-appended later to another node that is still connected to the tree.

Thanks for help.

Upvotes: 0

Vladu Ionut
Vladu Ionut

Reputation: 8193

JavaScript is automatically garbage collected; the object's memory will be reclaimed only if the Garbage Collectior decides to run and the object is eligible for that. You don't need to delete this inside the _destroy function just remove all its references.

function ZPNode(){}; //Constructor 
function _destroy(){ 
    //this = null; --> Won't work obviously 
} 
ZPNode.prototype.remove = function(){ 
    //Remove node 
    _destroy.call(this); 
}; 

An option if you want to achieve this is to nullify your Object instance, but that doesn't guarantees that another reference is still pointing to that object.

var obj = new ZPNode();
obj = null;

Upvotes: 2

Related Questions