Object-Oriented Programming (OOP) is a programming style based on the concept of "objects" — data structures that contain properties and methods. JavaScript supports OOP using objects and classes.
// Define a class
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
// Create an object
const dog = new Animal("Dog");
dog.speak(); // Output: Dog makes a sound.
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const myDog = new Dog("Rex");
myDog.speak(); // Output: Rex barks.
OOP helps you organize your code better, reuse it efficiently, and make large projects easier to manage.
There are multiple ways to create objects in JavaScript: object literals, constructors, and Object.create()
.
const person = { name: "Alice", age: 30, greet: function() { console.log("Hello, " + this.name); } }; person.greet(); // Output: Hello, Alice
You can create objects using a constructor function.
function Person(name, age) { this.name = name; this.age = age; this.greet = function() { console.log("Hello, " + this.name); }; } const person1 = new Person("Bob", 25); person1.greet(); // Output: Hello, Bob
The Object.create()
method creates a new object with the specified prototype object.
const personPrototype = { greet: function() { console.log("Hello, " + this.name); } }; const person2 = Object.create(personPrototype); person2.name = "Charlie"; person2.greet(); // Output: Hello, Charlie
Objects can contain properties (key-value pairs) and methods (functions).
const car = { make: "Toyota", model: "Corolla", year: 2020 }; console.log(car.make); // Output: Toyota console.log(car["model"]); // Output: Corolla
const car = { make: "Toyota", model: "Corolla", year: 2020, getCarInfo: function() { return `${this.year} ${this.make} ${this.model}`; } }; console.log(car.getCarInfo()); // Output: 2020 Toyota Corolla
this
KeywordThe this
keyword refers to the object that the function is a method of.
const person = { name: "David", greet: function() { console.log("Hello, " + this.name); } }; person.greet(); // Output: Hello, David
Prototypes allow objects to inherit properties and methods from other objects.
function Animal(name) { this.name = name; } Animal.prototype.speak = function() { console.log(this.name + " makes a sound"); }; const dog = new Animal("Rex"); dog.speak(); // Output: Rex makes a sound
JavaScript objects have a prototype, and that prototype can have its own prototype, forming a chain.
function Animal(name) { this.name = name; } Animal.prototype.speak = function() { console.log(this.name + " makes a sound"); }; function Dog(name, breed) { Animal.call(this, name); // Call the Animal constructor this.breed = breed; } Dog.prototype = Object.create(Animal.prototype); // Set Dog's prototype to be an instance of Animal Dog.prototype.constructor = Dog; Dog.prototype.bark = function() { console.log(this.name + " barks"); }; const dog = new Dog("Buddy", "Golden Retriever"); dog.speak(); // Output: Buddy makes a sound dog.bark(); // Output: Buddy barks
JavaScript supports Object-Oriented Programming (OOP) principles like encapsulation, inheritance, and polymorphism.
Encapsulation means grouping related data and the functions that manipulate that data within a class.
Information hiding:
It also involves hiding the internal implementation details of a class from the outside world.
Controlled access:
Encapsulation allows controlled access to the object's data and behavior, often using access modifiers like private or protected to restrict direct access to certain attributes or methods.
function Person(name, age) { this.name = name; this.age = age; this.getDetails = function() { return `${this.name} is ${this.age} years old.`; }; } const person = new Person("John", 25); console.log(person.getDetails()); // Output: John is 25 years old.
Polymorphism means "many forms" and refers to the ability of an object or method to exhibit different behaviors depending on the specific object it's acting on or the context in which it's used.
Method overriding:
A common example of polymorphism is method overriding, where a subclass provides a specific implementation of a method inherited from a parent class.
Method overloading:
Another form of polymorphism is method overloading, where multiple methods with the same name can have different parameters, allowing them to handle different input types or scenarios.
Benefits:
Polymorphism allows for flexible and extensible code, enabling code to be reused and adapted to different types of objects or situations.
function Animal(name) { this.name = name; } Animal.prototype.speak = function() { console.log(this.name + " makes a sound"); }; function Dog(name) { Animal.call(this, name); } Dog.prototype = Object.create(Animal.prototype); Dog.prototype.speak = function() { console.log(this.name + " barks"); }; function Cat(name) { Animal.call(this, name); } Cat.prototype = Object.create(Animal.prototype); Cat.prototype.speak = function() { console.log(this.name + " meows"); }; const dog = new Dog("Rex"); const cat = new Cat("Whiskers"); dog.speak(); // Output: Rex barks cat.speak(); // Output: Whiskers meows