Mo Gorhom
Mo Gorhom

Reputation: 31

JS Class Abstraction

I have been trying to create an abstract class that can modify variables from the inheriting class, but i am facing an issue when i set an empty variable in the inheriting class, the abstract class won't set it ?

this example DO NOT WORK

class Abc {
  constructor() {
    this.id = "x";
  }
}
class Test extends Abc {
  id;
}

const test = new Test();
console.log(test)

this example DO WORK

class Abc {
  constructor() {
    this.id = "x";
  }
}
class Test extends Abc {
}

const test = new Test();
console.log(test)

Upvotes: 3

Views: 285

Answers (1)

Ali Habibzadeh
Ali Habibzadeh

Reputation: 11548

You can initialise them your id with undefined but also set it an optional field in constructor in case you want to set in when creating instance.

You can't have abstract classes in JS but you can add a simple validation to prevent direct instantiations:

class AbstractClass {
  constructor(id = undefined) {
    if (new.target.name === AbstractClass.name) {
      throw new Error("Can not create instance of Abstract class");
    }
    this.id = id;
  }
}

class DerivedClass extends AbstractClass {}

const disallowed = new AbstractClass(); // throws error 
const allowed = new DerivedClass(1); // will work fine

Upvotes: 1

Related Questions