gpt4 book ai didi

javascript - 对类属性的引用为空

转载 作者:行者123 更新时间:2023-11-29 15:13:45 25 4
gpt4 key购买 nike

我的印象是对象的任何部分都是通过引用设置的。在这个例子中似乎不是这种情况

class System {}

class Foo {
constructor() {
this.system = null;
this.dictionary = {
system: this.system
}
}
}

class Bar extends Foo {
constructor() {
super();
this.system = new System();
}
}

var bar = new Bar();
console.log(bar.system); // System{}
console.log(bar.dictionary.system); // null

我希望 dictionary 持有对以 null 开头的 this.system 的引用,但这只是因为它引用的是。然而可以看出,bar.dictionary.system 实际上仍然是 null,即使它的引用已更新。

谁能解释一下这里发生了什么?

最佳答案

它仍然是通过引用设置的。这里的问题是,通过编写 this.system = new System(),您并没有修改引用的值,而是让 this.system 引用了一个完全不同的值.与此同时,this.dictionary.system 仍然指向旧值。

考虑以下代码:

class Foo {
constructor() {
this.system = {};
this.dictionary = { system: this.system };
}
}
class Bar {
constructor() {
super();
this.system.bananas = 5;
}
}

这会正确地将香蕉添加到 this.systemthis.dictionary.system,因为您正在修改被引用的值,而不是制作 this。 system 引用了一个完全不同的值。

关于javascript - 对类属性的引用为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51542075/

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