gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:31:20 25 4
gpt4 key购买 nike

我目前正在学习如何使用 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 = new this.constr(num); 工作正常,但下面的代码给出了所描述的错误。这是为什么?为什么 b.left 可以赋值,而 b 本身不能赋值? bthis.a 引用的不是同一个对象吗?

最佳答案

当您将 this.a 分配给 b 时,它包含分配给 this.anull 的引用, 它无法引用属性 a;当您为 b = new this.constr(num); 分配新值时,b 变量引用新对象,而不是更改属性 a那个对象。

关于javascript - 无法使用对象读取 null 的属性 'data',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47239427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com