Javascript 无法读取属性';数据';使用对象创建空值

Javascript 无法读取属性';数据';使用对象创建空值,javascript,object,Javascript,Object,我目前正在学习如何在Javascript中实现二进制搜索树。我遇到了一个错误“无法读取null的属性‘数据’”,我能够修复这个错误,但我仍然无法理解为什么它会出现这个错误 以下是我的代码的简化版本: var test = function(){ this.a = null; this.constr = function(val){ this.data = val; this.left = null; return this;

我目前正在学习如何在Javascript中实现二进制搜索树。我遇到了一个错误“无法读取null的属性‘数据’”,我能够修复这个错误,但我仍然无法理解为什么它会出现这个错误

以下是我的代码的简化版本:

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=newthis.constr(num)工作正常,但下面的代码给出了描述的错误。为什么呢?为什么可以分配b.left而不能分配b本身?bthis.a是否引用了同一个对象?

当您将
this.a
分配给
b
时,它持有分配给
this.a
null
的引用,它绝不会引用属性
a
;当您为
b=newthis.constr(num)分配新值时
变量引用新对象,而不是更改该对象的属性
a

分配给
b
不会分配给
this.a
。变量永远不是对属性的引用(除非将
一起使用)。是的,当
b
this.a
引用同一个对象时,则更改该对象的属性不会产生任何影响。但是
b
保留您在条件中确定的值
null
。@Bergi感谢您的回答我发现您的回答非常有用,并使我意识到我在做什么。