Search code examples
javascriptinheritanceprototypees6-class

ES6 child class inheritance property


I have a parent A and two other classes B and C that extend A. I'm trying to change the config property inside the parent class A from a child, for example B, and be shared automatically with other childs, for example C?

class A {
   constructor() {
       this.config = {};
   }
}

class B extends A {
    constructor() {
        super();
    }
   updateConfig() {
       this.config = "B";
   }
}

class C extends A {
    constructor() {
        super();
    }
    getConfig() {
        console.log(this.config);
    }
}

const b = new B();
const c = new C();
b.updateConfig();
c.getConfig(); // got {} expected "B"

Solution

  • b and c are completely different objects. While they both derive from A (which means they inherit behavior, not data), they are separate instances and thus have separate instance data. So, they each have their own section of their object that is an A. When you change the A part of b, it does not affect the A part of c.

    If you want a single value that is shared by all instances, perhaps you want to use a static property of one of your classes or perhaps you want each of b and c to have a reference to the same object in their instance data so when one changes that object, the other will see the same change (because they're both referring to the same object).