Object-Oriented Programming
ES6 Classes and Objects
Objects
In the real world, everything can be considered an object - a concrete entity that can be seen and touched. For instance, a book, a car, or a person can be objects. Similarly, a database connection, a web page, or a server connection can also be treated as objects.
Objects consist of properties and methods:
- Properties: Characteristics of an entity (typically nouns)
- Methods: Behaviors of an entity (typically verbs)
In JavaScript, an object is an unordered collection of related properties and methods. Everything in JavaScript is an object, including strings, numbers, arrays, and functions.
Classes
ES6 introduced the concept of classes using the class keyword. Classes allow us to create blueprints for objects, which can then be instantiated.
A class abstracts common features from objects and represents a general category, while an object is a specific instance created from a class.
Creating a Class
class ClassName {
// class body
}
Creating an Instance:
let instance = new ClassName();
Note: Classes must be instantiated using the new keyword.
Class Constructor
The constructor() method is a special method in a class that serves as the constructer. It's used to initialize parameters and return instance objects. This method is automatically called when creating an object instance with the new keyword. If not explicitly defined, the class automatically creates an empty constructor.
Syntax:
class Human {
constructor(fullName, birthYear) {
this.fullName = fullName;
this.birthYear = birthYear;
}
}
Creating an Instance:
let person = new Human('John Smith', 1990);
console.log(person.fullName);
Adding Methods to Classes
Note: Methods should not be separated by commas and do not require the function keyword.
class Human {
constructor(fullName, birthYear) {
this.fullName = fullName;
this.birthYear = birthYear;
}
greet() {
console.log(`Hello, my name is ${this.fullName}`);
}
}
Creating an Instance:
let person = new Human('John Smith', 1990);
person.greet();
Class Inheritance
In real life, inheritance means children inherit from their parents. In programming, inheritance allows a child class to inherit properties and methods from a parent class.
Syntax:
class Parent {
}
class Child extends Parent {
}
Example:
class Vehicle {
constructor(brand) {
this.brand = brand;
}
displayBrand() {
console.log(`This vehicle is made by ${this.brand}`);
}
}
class Car extends Vehicle {
}
let myCar = new Car('Toyota');
myCar.displayBrand();
The super keyword is used to access and call functions on an object's parent class. It can invoke the parent's constructor or regular methods.
Note: When using super in a subclass constructor, it must be placed before this.
class Animal {
constructor(species) {
this.species = species;
}
}
class Mammal extends Animal {
constructor(species, habitat) {
super(species);
this.habitat = habitat;
}
}
Example:
class Employee {
constructor(department) {
this.department = department;
}
showDepartment() {
console.log(`I work in the ${this.department} department`);
}
}
class Manager extends Employee {
constructor(department, teamSize) {
super(department);
this.teamSize = teamSize;
}
showTeamSize() {
console.log(`I manage a team of ${this.teamSize} people`);
}
}
let teamLead = new Manager('Engineering', 8);
teamLead.showDepartment();
teamLead.showTeamSize();
The super keyword can also call parent class methods:
class Shape {
describe() {
return 'I am a geometric shape';
}
}
class Circle extends Shape {
describe() {
return super.describe() + ' with no edges';
}
}
let circle = new Circle();
console.log(circle.describe());
Important Points:
- In ES6, classes do not have hoisting. You must define a class before instantiating it.
- Shared properties and methods within a class must use
this. - Be mindful of
thiscontext within classes. In constructors,thispoints to the instance, while in methods,thispoints to the method caller.
Example 1:
class Device {
getType() {
return 'electronic device';
}
}
class Smartphone extends Device {
getType() {
console.log(`I am a ${super.getType()} that you can carry`);
}
}
let phone = new Smartphone();
phone.getType();
Example 2:
class Calculator {
constructor(valueA, valueB) {
this.valueA = valueA;
this.valueB = valueB;
}
add() {
console.log(this.valueA + this.valueB);
}
}
class AdvancedCalculator extends Calculator {
constructor(valueA, valueB) {
super(valueA, valueB);
}
multiply() {
console.log(this.valueA * this.valueB);
}
}
let calc = new AdvancedCalculator(6, 4);
calc.multiply();
calc.add();