【问题标题】:Why can't I set "this" to null to delete a tree node in Javascript?为什么我不能将“this”设置为 null 以删除 Javascript 中的树节点?
【发布时间】:2018-04-19 22:11:03
【问题描述】:

我试图删除一棵树中的一个根节点,而这棵树只有一个节点。由于“this”指的是节点的当前上下文,因此我将其设置为 null 执行 this = null;(下面代码的案例 2)。但是,我收到一条错误消息:ReferenceError: Invalid left-hand side in assignment。一种解决方法是使用delete this.val;(案例1)。

我的问题:为什么我不能设置this = null; 来删除树对象?另一种删除 obj 的方法?谢谢你。

var BST = function(val) {
  this.val = val;
  this.left = null;
  this.right = null;
}

BST.prototype.remove = function(val) {
  //delete this.val;  // Case 1: OK
  this = null;        // Case 2: WRONG !
}

BST.prototype.printTree = function() {
  if (this === undefined) {
    return;
  } else
    console.log(this.val);
}

var bst = new BST(70);
bst.remove(70);
bst.printTree();

【问题讨论】:

标签: javascript


【解决方案1】:

this 是 javascript 中的关键字,不应位于赋值的左侧,例如此处(案例 2):this = null

当您执行delete this.val;(案例1)时,您将从this 在函数范围内表示的任何上下文中删除属性val(BST,在您的情况下,因为它是一个原型函数)。

我相信您需要重构代码以使用根节点或父节点执行分支删除。喜欢:

BST.prototype.remove = function(branchToDeleteRef) {
    this[branchToDeleteRef] = null;
}

如果您使用this.val = null,它也可以工作,就像在这个fiddle 中一样。

【讨论】:

    【解决方案2】:

    一旦对您的对象的所有引用都消失了,它就会被清理干净。因此,如果 this.leftthis.right 也是树,则将 this.leftthis.right 设置为 null 将删除这些树,如果没有其他对它们的引用。换个角度来看,您可以通过从父节点中删除节点来删除节点,而不是从自身中删除节点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 2019-04-03
      相关资源
      最近更新 更多