Object-Oriented Programming (OOP) in JavaScript is a way to build objects from blueprints (classes) and boost code reusability.
🎯 OOP Principles:
• Encapsulation: Bundling data and methods together into a single object
• Inheritance: A child class picking up properties from a parent class
• Polymorphism: Using methods in different ways depending on the context
• Abstraction: Hiding away complex details
javascript
// Constructor function (Old way)
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
return `Hello, I'm ${this.name}`;
};
}
const person1 = new Person("Aung Kyaw", 25);
console.log(person1.greet());
console.log(`Age: ${person1.age}`);
// ES6 Class (Modern way)
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}
const dog = new Animal("Buddy");
console.log(dog.speak());You should see
Hello, I'm Aung Kyaw Age: 25 Buddy makes a sound