如何将当前对象设置为null?
function ZPNode(){}; //Constructor
function _destroy(){
//this = null; --> Won't work obviously
}
ZPNode.prototype.remove = function(){
//Remove node
_destroy.call(this);
};
编辑:也许描述不清楚。应该发生的事情是:
var tree = ZPTree.create(jsonArr);
var node = tree.findNode(1);
node.remove();
console.log(node); //null
原因很简单。你不想意外地做一些事情:
node.remove();
node.appendChild(anotherNode); //Oops
如果没有其他方法,可能的解决方案是在对象上使用状态。
Edit2:经过更多的研究,我不认为这是可能的。我不情愿地采用一种解决方案。我可以这样做:
tree.removeNode(node);
虽然在我看来它看起来不太干净。
答案 0 :(得分:2)
JavaScript自动被垃圾收集;只有当Garbage Collectior决定运行且对象符合条件时,才会回收对象的内存。您不需要删除 _destroy 函数中的 this ,只需删除其所有引用。
function ZPNode(){}; //Constructor
function _destroy(){
//this = null; --> Won't work obviously
}
ZPNode.prototype.remove = function(){
//Remove node
_destroy.call(this);
};
如果要实现此目的,则选项是使Object实例无效,但这并不能保证另一个引用仍指向该对象。
var obj = new ZPNode();
obj = null;
答案 1 :(得分:0)
最终,我为我的具体用例找到了最合理的解决方案 就像将当前树的引用设置为0一样简单。
this._treeId = 0;
节点继续存在并不重要,因为它不再连接到树了 更重要的是,保持节点存在是有意义的,因为它可以稍后重新附加到仍然连接到树的另一个节点。
感谢您的帮助。