Home > database >  Use static property of extended class in super()
Use static property of extended class in super()

Time:08-13

Suppose we have the code

class A {
  static foo = 1;
  constructor() {
    console.log(A.foo);
  }
}
class B extends A {
  static foo = 2;
  constructor() {
    super();
  }
}
new A(); // prints "1"
new B(); // also prints "1", but make it print "2"

Here the constructor of A is accessing A.foo. When A is extended to B with a new value of foo, the constructor still prints 1, the value of A.foo, when really I want it to print the value of B.foo.

How would I modify this code such that the constructor prints the foo property of the current class?

CodePudding user response:

Use the constructor property to get access to the class itself, then you can refer to the static property from that.

class A {
  static foo = 1;
  constructor() {
    console.log(this.constructor.foo);
  }
}
class B extends A {
  static foo = 2;
  constructor() {
    super();
  }
}
new A(); // prints "1"
new B(); // also prints "1", but make it print "2"

CodePudding user response:

the super calls the constructor of the super class.

What you can do is the following

class A {
      static foo = 1;
      constructor(...args) {
        if(args.length == 1){
          console.log(args[0].foo)
        }
        else{
        
        console.log(A.foo);
        }
      }
    }
    
class B extends A {
  static foo = 2;
  constructor(...args) {
    super(...args); // calls A.foo not B.foo
  }
}
new A(); // prints "1"
new B(B); // pass the Class to it self as an arg

  • Related