Published on

Object-Oriented Programming in JavaScript

The House Analogy 🏠

Imagine you want to build a house. Before you start building, you need a blueprint, which is like a template that defines the structure and layout of the house. In programming, a blueprint is called a class.

The instances that you create from a class are called objects. Think of an object as a specific implementation of a class, like a specific house built from a blueprint. Each instance could have various of properties values, for example some houses could be in green color, and some could be in pink color.

OOP is important and useful because it helps you organize your code and make it more reusable. Instead of writing a lot of redundant code, you can create a class and use it to create multiple objects with similar properties and behaviors. This makes your code more modular, easier to maintain, and easier to understand.

Example of paying money 💰

Now, let's take a look at how we could apply the OOP concept.

Imagine you need to pay someone some money. We can create a class called Person which would have properties like name and money. The class would also have methods (or functions) that define what the object can do. In our case, we can have a pay method for the person who wants to pay the money, and a receive method for the person who will receive the money.

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

  pay(amount, receiver) {
    this.money -= amount;
    receiver.receive(amount);
  }

  receive(amount) {
    this.money += amount;
  }
}

const person1 = new Person("Alice", 100);
const person2 = new Person("Bob", 50);

person1.pay(30, person2);

console.log(person1.money); // Output: 70
console.log(person2.money); // Output: 80

In the above code snippet, we have a Person class that takes two parameters in its constructor function: name and money. We also have two methods: pay and receive. The pay method takes an amount and a receiver object as parameters. It subtracts the amount from the person's money property and calls the receiver object's receive method, passing in the amount. The receive method simply adds the amount to the person's money property.

In this example, we create two Person objects called person1 and person2. We then call the pay method on person1, passing in the amount of 30 and the person2 object as the receiver. The pay method subtracts 30 from person1's money property and calls person2's receive method, passing in 30. The end result is that person1 has 70 dollars left, and person2 has 80 dollars.

Conclusion

In conclusion, Object-Oriented Programming is a powerful concept that can make your code more organized and easier to reuse. By creating classes and objects with properties and methods, you can create code that easily mimics real-life situations.