Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

JavaScript Essentials - Object-Oriented Programming

Implementing OOP concepts in JavaScript

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects," which can contain data and code. This tutorial covers the basics of implementing OOP concepts in JavaScript, including classes, objects, inheritance, encapsulation, and polymorphism.

Key Points:

  • OOP helps organize code into reusable and modular components.
  • JavaScript supports OOP through prototypes and ES6 classes.
  • Understanding OOP concepts is essential for building scalable and maintainable applications.

Classes and Objects

In JavaScript, classes are templates for creating objects. Objects are instances of classes and can have properties and methods. Here is an example:


class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    greet() {
        return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
    }
}

const alice = new Person('Alice', 30);
console.log(alice.greet()); // Output: Hello, my name is Alice and I am 30 years old.
                

Inheritance

Inheritance allows a class to inherit properties and methods from another class. In JavaScript, you can use the extends keyword to create a subclass. Here is an example:


class Animal {
    constructor(name) {
        this.name = name;
    }

    speak() {
        console.log(`${this.name} makes a sound.`);
    }
}

class Dog extends Animal {
    speak() {
        console.log(`${this.name} barks.`);
    }
}

const dog = new Dog('Rex');
dog.speak(); // Output: Rex barks.
                

Encapsulation

Encapsulation is the concept of restricting access to certain properties or methods of an object. In JavaScript, you can use private fields to achieve encapsulation. Here is an example:


class Counter {
    #count = 0;

    increment() {
        this.#count++;
    }

    getCount() {
        return this.#count;
    }
}

const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // Output: 1
                

Polymorphism

Polymorphism is the ability to call the same method on different objects and have each object respond in a way appropriate to itself. Here is an example:


class Shape {
    area() {
        return 0;
    }
}

class Circle extends Shape {
    constructor(radius) {
        super();
        this.radius = radius;
    }

    area() {
        return Math.PI * this.radius * this.radius;
    }
}

class Rectangle extends Shape {
    constructor(width, height) {
        super();
        this.width = width;
        this.height = height;
    }

    area() {
        return this.width * this.height;
    }
}

const shapes = [new Circle(5), new Rectangle(4, 6)];
shapes.forEach(shape => {
    console.log(shape.area());
});
// Output:
// 78.53981633974483
// 24
                

Composition

Composition is a design principle where you build complex objects by combining simpler ones. It is often preferred over inheritance. Here is an example:


const canEat = {
    eat: function() {
        console.log('Eating...');
    }
};

const canWalk = {
    walk: function() {
        console.log('Walking...');
    }
};

function Person(name) {
    this.name = name;
}

Object.assign(Person.prototype, canEat, canWalk);

const person = new Person('Alice');
person.eat(); // Output: Eating...
person.walk(); // Output: Walking...
                

Summary

In this tutorial, you learned about implementing OOP concepts in JavaScript, including classes and objects, inheritance, encapsulation, polymorphism, and composition. Understanding these OOP concepts is essential for building scalable, maintainable, and modular JavaScript applications.