Home > OS >  Can't use "super.member.Func()" in javascript. How to rewrite it correctly?
Can't use "super.member.Func()" in javascript. How to rewrite it correctly?

Time:11-30

super in JS In this I read what can't use super as it:

class Base {
  baseField = 10;
}

class Extended extends Base {
  extendedField = super.baseField; // undefined
}

My code is:


class Parent{
   ext_class;
   constructor(ext){
   this.ext_class=ext;
   }
}

class Child extends Parent{
   constructor(ext){
      super(ext);
   }
   Method(p){
      super.ext_class.ExecFunc(p);
   }


}

I can't call function from object in member of parent class. I can save it in child but not sure what it is right.

How do I write it correctly?

class Base {
  constructor(bf){
    this.baseField = bf
  }
}

Base.prototype.baseField = 1;

class Extended extends Base {
  constructor(bf){
    super(bf)
  }
  extendedField = super.baseField;
}

console.log(new Extended(12).extendedField);

This not work correctly too.

But this work how I need!!!

class Base {
  constructor(bf){
    Base.prototype.baseField = bf
  }
}

class Extended extends Base {
  constructor(bf){
    super(bf)
  }
  extendedField = super.baseField;
}
console.log(new Extended(13).extendedField);

CodePudding user response:

I think you should've scrolled further down:

Note that instance fields are set on the instance instead of the constructor's prototype, so you can't use super to access the instance field of a superclass.

That means you'd have to put the property on the prototype explicitly like this:

class Base {}

Base.prototype.baseField = 10;

class Extended extends Base {
  extendedField = super.baseField;
}

console.log(new Extended().extendedField);

  • Related