MENU
Abstract Class
An abstract class, sometimes also called a template, is a class from which an object cannot be instantiated directly.
As of July 2017, there is no native support for abstract classes and interfaces. However, you can do the following:
class Food {
constructor(b) {
if (new.target === Food) // or: this.contructor === Food
throw new TypeError("Cannot instantiate from an Abstract Class directly! Food");
if (this.brand === undefined)
throw new TypeError("brand() must be defined -- Food");
}
}
class DogFood extends Food {}
// var h = new Food;
var o = new DogFood;Uncaught TypeError: brand() must be defined -- Food
(if "var h = new Food;" above were uncommented, it would throw first: Uncaught TypeError: Cannot instantiate from an Abstract Class directly! Food)
Every time a 'new' keyword is used to instantiate an object (eg. new Food), the class (ie. Food)is assigned to a meta property, new.target, which can be accessed within the constructor.