如何在 class 创建的对象和 javascript 中扩展的 class 对象之间建立引用?

How to make a reference between objects created by class and extended class in javascript?

我创建了两个 classes:

class MyFirstClass {
    constructor(fname, lname, date) {
        this.fname = fname;
        this.lname = lname;
        this.date = date;
    }
}

class MySecondClass extends MyFirstClass {
    constructor(id, optionalArg) {
        super();
        this.id = id;
    }
}

然后像这样创建了两个对象:

let myFirstObj = new MyFirstClass("foo", "bar", "today");
let mySecondObj = new MySecondClass(1234); //***(1234, optionalArg)

现在,有几种方法可以将属性从第一个 class 实际传递到另一个(或从第一个对象到第二个),但是无论我做什么,第二个对象都不会引用第一个对象,它只是创建它的拥有 "copy" 的财产。所以当我这样做时:

mySecondObj.fname = "someothername";

第一个对象没有改变——它没有引用第二个对象(或者相反——也不起作用)。 我的问题是:如何解决这个 "conection" on classes (or out of them) 实际引用新对象? 我想让它尽可能简单(这就是为什么我在第二个 class 中留下可选参数)。

创建 class 继承并不意味着它们通过引用隐式共享值。所以 myfirstobj 和 mysecondobj 会在内存中占据它们自己的 space,并且对它们中的任何一个所做的更改都不会自动更改它们的对应部分。

这里尝试使用 getset 来维护两个对象之间的引用连接。

见下文并阅读评论。

class MyFirstClass {
    constructor(fname, lname, date) {
        this.f_name = fname;
        this.f_name = lname;
        this.d = date;
        this.b = this;
       
    }
    
    set base(value){
        this.b = value;
        var a = this;
        
        Object.keys(this).forEach(function(key){
           if (a.b[key] != undefined)
               a[key] =a.b[key]
        });
    }
    
    set fname(value){
      this.f_name = this.b.f_name = value; 
    }
    
    get fname(){
      return this.f_name;
    }
    
    get lname(){
     return this.l_name; 
    }
    
    set lname(value){
      this.l_name =this.b.l_name= value; 
    }
    
    set date(value){
      this.d =this.b.d= value; 
    }
    
    get date(){
       return this.d;
    }
    
}

class MySecondClass extends MyFirstClass {
    constructor(id,base,optionalArg) {
        super();
        this.id = id;
         // chooce to have a reference to another object as base
         // now when you change either this or base class the both of them will change to
        if (base){
            this.base = base;
            base.b = this;
           }
    }
}

let myFirstObj = new MyFirstClass("foo", "bar", "today");
// myFirstObj is optional. 
let mySecondObj = new MySecondClass(1234, myFirstObj); //***(1234,base, optionalArg)

mySecondObj.fname = "test"

console.log(myFirstObj.fname)