Simple Guide to OOP in JavaScript

What is OOP?

Think of Object-Oriented Programming (OOP) like building with LEGO blocks. In OOP, these blocks are called "objects." Each object is like a mini-program with its own information and actions it can do. Putting these objects together, you can create a bigger program.

Key OOP Ideas in JavaScript:

  1. Objects: Imagine you have a toy box. Inside, each toy has a name and things it can do (like a toy car can roll). In JavaScript, this toy box is an object.
const toyCar = {
    name: 'Speedy',
    action: function() {
        console.log('Rolling!');
    }
};
toyCar.action();  // It says: Rolling!
  1. Prototypes: Think of prototypes as parents teaching their kids. If a kid doesn't know something, they ask their parent. In JavaScript, if an object doesn't have a particular action, it asks its prototype.
function Toy(name) {
    this.name = name;
}
Toy.prototype.play = function() {
    console.log('Playing with ' + this.name);
};
const teddyBear = new Toy('Teddy');
teddyBear.play();  // It says: Playing with Teddy
  1. Classes: Classes are like blueprints. If you have a blueprint for a toy, you can make many toys using that design. With the newer versions of JavaScript, you can use classes to make objects easily.
class Toy {
    constructor(name) {
        this.name = name;
    }
    play() {
        console.log('Playing with ' + this.name);
    }
}
  1. Inheritance: Imagine a general toy blueprint. Now, you want to create a blueprint for a specific toy, like a toy robot, but you don't want to start from scratch. You can use the general blueprint and just add robot features. That's inheritance.
class ToyRobot extends Toy {
    robotDance() {
        console.log(this.name + ' does the robot dance!');
    }
}
  1. Keeping Secrets (Encapsulation): Sometimes, a toy has secret buttons only you know about. Similarly, in JavaScript, objects can keep some information hidden.
class SecretBox {
    #secretItem = 'Gold coin';
    showSecret() {
        return this.#secretItem;
    }
}

In Short:

OOP in JavaScript is like playing with toys. Each toy (or object) has its own details and things it can do. By understanding these basic ideas, you can build big and fun programs just like building a large LEGO set!