Overview
- Are used to create blueprint to create instances of multiple objects
- The constructor is invoked every time we create/initialise a new object using the class
class Dog { constructor(name) { this._name = name; this._behavior = 0; } get name() { return this._name; } get behavior() { return this._behavior; } incrementBehavior() { this._behavior ++; } } const zuzu = new Dog('name'); // instance
Inheritance
With inheritance, we can create a parent class (also known as a superclass) with properties and methods that multiple child classes (also known as subclasses) share. The child classes inherit the properties and methods from their parent class.
class Animal { constructor(name) { this._name = name; this._behavior = 0; } get name() { return this._name; } get behavior() { return this._behavior; } incrementBehavior() { this._behavior++; } } class Cat extends Animal { constructor(name, usesLitter) { super(name); this._usesLitter = usesLitter; } }
- The
extendskeyword makes the properties and methods of the Animal class available inside the Cat class.
- The constructor, called when a new Cat object is created, accepts two arguments, name and usesLitter.
- The
superkeyword calls the constructor of the parent class. In this case,super(name)passes the name argument of theCatclass to the constructor of the Animal class. When the Animal constructor runs, it sets this._name = name; for new Cat instances. _usesLitter is a new property that is unique to the Cat class, so we set it in the Cat constructor.
- In a subclass constructor, we must always call the super() method before using the this keyword — if we do not, JavaScript will throw a reference error.
- The instances will all have all the methods from their parent class
- Child classes can contain their own properties, getters, setters and methods
Static Methods
- Sometimes, we want a class to have methods that aren’t available in individual instances but can be called directly from the class.
- Take the Date class, for example — we can both create
Dateinstances to represent whatever date we want, and call static methods, likeDate.now()which returns the current date, directly from the class.
- The
.now()method is static, so it can be called directly from the class, but not from an instance of the class.
class Animal { constructor(name) { this._name = name; this._behavior = 0; } static generateName() { const names = ['Angel', 'Spike', 'Buffy', 'Willow', 'Tara']; const randomNumber = Math.floor(Math.random()*5); return names[randomNumber]; } }