【问题标题】:Set current object to null将当前对象设置为空
【发布时间】:2016-05-26 08:16:59
【问题描述】:

如何将当前对象设置为空?

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); 

虽然在我看来它看起来不那么干净。

【问题讨论】:

  • 我觉得你应该看看this answer
  • 虽然,它不会删除对象本身。你的函数remove没有效果
  • 你为什么要这样做?
  • @Rayon 因为当用户从树中删除一个节点时,它应该设置为空。我不想强迫他们进入 node=node.remove();

标签: javascript


【解决方案1】:

JavaScript 会自动进行垃圾回收;只有当垃圾收集器决定运行并且对象符合条件时,才会回收对象的内存。您无需在 _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;

【讨论】:

  • 这更像是一个api问题。当用户调用 node.remove(); (应该从树中删除当前节点),实例应该设置为空。我不希望他们强行进入 node = node.remove();
  • destroy实现函数示例_destroy(){ //这里可以删除对其他对象的引用 引用 delete this.element; //从dom中移除元素 this.elementNodeReference.remove(); //删除全局引用删除window.ZPNodeTree; // window.ZPNodeTree = null; }
  • 感谢您的意见
【解决方案2】:

最终我找到了适合我的特定用例的最合乎逻辑的解决方案。
就像将当前树的引用设置为 0 一样简单。

this._treeId = 0; 

节点是否继续存在实际上并不重要,因为它不再连接到树。
更重要的是,保持节点存在是有意义的,因为它可能稍后会重新附加到仍然连接到树的另一个节点。

感谢您的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 2016-09-29
    • 2015-05-25
    • 2015-02-16
    • 2019-05-15
    • 1970-01-01
    相关资源
    最近更新 更多