无法使用对象读取null属性'data'

问题描述:

我目前正在学习如何在Javascript中实现二叉搜索树。我遇到了一个错误“无法读取空值”属性'数据',我可以修复,但我仍然不明白为什么它给出了这个错误。无法使用对象读取null属性'data'

这里是我的代码的简化版本:

var test = function(){ 
    this.a = null; 

    this.constr = function(val){ 
     this.data = val; 
     this.left = null; 
     return this; 
    }; 

    this.create = function(num){ 
     var b = this.a; 

     if(b === null) 
      //this.a = new this.constr(num); 
      b = new this.constr(num); 
     else 
      b.left = new this.constr(num); 
    }; 
}; 

var c = new test(); 

c.create(5); 
c.create(20); 
console.log(c.a.data); 
console.log(c.a.left); 

,我在第14行评论的代码:this.a =新this.constr(NUM);工作正常,但下面的它给出了描述的错误。这是为什么?为什么可以分配b.left但不是b本身?是不是bthis.a引用同一个对象?当你将this.ab它拥有分配this.anull参考

+1

分配给'b'不会分配给'this.a'。变量永远不会是对属性的引用(除非您使用'with')。是的,当*'b'和'this.a'引用同一个对象时,*改变该对象的属性*并没有什么区别。但是'b'在你建立的条件下保存了'null'的值。 – Bergi

+0

@Bergi谢谢你的回复我发现你的回答真的很有用,并让我意识到我在做什么。 – Vektor

,它没有办法引用属性a;当您将新值赋予b = new this.constr(num);b变量引用了新对象,而不是修改该对象的属性a