JavaScript Object Oriented Programming
What is Object-Oriented Programming (OOP) in JavaScript?
Object-Oriented Programming (OOP) is a programming paradigm that uses "objects" to represent data and methods. In JavaScript, OOP allows for the creation of objects that can encapsulate state and behavior, promoting code reusability and organization.
What are the main principles of OOP?
The main principles of OOP include:
- Encapsulation: Bundling the data (properties) and methods (functions) that operate on the data into a single unit or object.
- Inheritance: A mechanism that allows one object to inherit properties and methods from another, enabling code reuse.
- Polymorphism: The ability to use a common interface for different data types, allowing for flexibility and integration.
- Abstraction: Hiding complex implementation details and exposing only the necessary parts of an object.
How do you create an object in JavaScript?
You can create an object in JavaScript using object literals, constructor functions, or the class syntax introduced in ES6.
// Object literal
const person = {
name: 'Alice',
age: 30,
greet() {
console.log(`Hello, my name is ${this.name}`);
}
};
// Constructor function
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
}
const alice = new Person('Alice', 30);
// ES6 class
class PersonClass {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
const bob = new PersonClass('Bob', 25);
What is the difference between a constructor function and a class in JavaScript?
Constructor functions are a traditional way to create objects and are defined using function declarations. Classes, introduced in ES6, provide a clearer syntax and features such as inheritance through extends and super constructors. Classes also do not require the use of the new keyword in their definition.
// Constructor function
function Car(make, model) {
this.make = make;
this.model = model;
}
const myCar = new Car('Toyota', 'Corolla');
// Class
class CarClass {
constructor(make, model) {
this.make = make;
this.model = model;
}
}
const myOtherCar = new CarClass('Honda', 'Civic');
How does inheritance work in JavaScript?
Inheritance allows one object to inherit properties and methods from another. In JavaScript, inheritance can be achieved using prototype chaining or the class syntax with the extends keyword.
// Prototype inheritance
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a noise.`);
};
function Dog(name) {
Animal.call(this, name); // Call the parent constructor
}
// Inherit from Animal
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
const dog = new Dog('Rex');
dog.speak(); // Rex makes a noise.
// Class inheritance
class AnimalClass {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class DogClass extends AnimalClass {
constructor(name) {
super(name); // Call the parent constructor
}
}
const dogClass = new DogClass('Rex');
dogClass.speak(); // Rex makes a noise.
What is encapsulation in JavaScript?
Encapsulation is the bundling of data (properties) and methods (functions) that operate on the data into a single unit, or object. It also refers to the practice of restricting access to certain properties and methods of an object to protect the integrity of the object's state.
class BankAccount {
#balance; // Private field
constructor(initialBalance) {
this.#balance = initialBalance;
}
deposit(amount) {
this.#balance += amount;
console.log(`Deposited: ${amount}`);
}
getBalance() {
return this.#balance; // Accessing private field
}
}
const account = new BankAccount(100);
account.deposit(50);
console.log('Current Balance:', account.getBalance()); // Current Balance: 150
What is polymorphism in JavaScript?
Polymorphism allows objects of different classes to be treated as objects of a common superclass. It is typically achieved through method overriding, where a subclass provides a specific implementation of a method that is already defined in its superclass.
class Animal {
speak() {
console.log('Animal speaks');
}
}
class Dog extends Animal {
speak() {
console.log('Dog barks');
}
}
class Cat extends Animal {
speak() {
console.log('Cat meows');
}
}
const animals = [new Dog(), new Cat()];
animals.forEach(animal => animal.speak());
// Outputs:
// Dog barks
// Cat meows
How can you create private properties in JavaScript?
You can create private properties in JavaScript using the # syntax in class fields or using closures to encapsulate variables within a function.
// Using private class fields
class Person {
#age; // Private field
constructor(name, age) {
this.name = name;
this.#age = age;
}
getAge() {
return this.#age; // Accessing private field
}
}
// Using closures
function createCounter() {
let count = 0; // Private variable
return {
increment: function() {
count++;
return count;
},
getCount: function() {
return count;
}
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.getCount()); // 1