JavaScript is a versatile programming language that allows you to implement Object-Oriented Programming (OOP) concepts. Here's how you can do it:
Objects and Classes:
class
keyword and give it a meaningful name.new
keyword.class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name}!`);
}
}
const john = new Person('John Doe', 25);
john.sayHello();
Inheritance:
extends
keyword to create a subclass that inherits from a base class.super()
within the subclass constructor.class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
introduce() {
console.log(`I am a student in ${this.grade}th grade.`);
}
}
const alice = new Student('Alice Smith', 16, 10);
alice.sayHello();
alice.introduce();
Encapsulation:
public
, protected
, private
) to control the visibility and accessibility of properties and methods of a class.Polymorphism:
class Animal {
speak() {
console.log('Animal makes a sound.');
}
}
class Dog extends Animal {
speak() {
console.log('Dog barks!');
}
}
const dog = new Dog();
dog.speak(); // Output: Dog barks!
These are the fundamental concepts of OOP in JavaScript. By leveraging them, you can write more organized and modular code, making it easier to maintain and extend your applications.