Javascript - Object-Oriented JavaScript

Object-Oriented JavaScript (OOP in JavaScript)

Introduction to Object-Oriented JavaScript

Object-Oriented JavaScript (OOP in JavaScript) is a powerful programming paradigm that allows developers to structure code using objects, classes, and reusable components. JavaScript, being a prototype-based language, provides flexible ways to implement object-oriented programming concepts such as encapsulation, inheritance, abstraction, and polymorphism.

In modern web development, understanding Object-Oriented JavaScript is essential for building scalable, maintainable, and reusable applications. Whether you are working on frontend frameworks or backend development using Node.js, mastering OOP concepts helps in writing clean and efficient code.

What is Object-Oriented Programming (OOP)?

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects. Objects contain properties (data) and methods (functions). OOP helps organize code into reusable structures, improving readability and maintainability.

Core Principles of OOP

  • Encapsulation
  • Inheritance
  • Polymorphism
  • Abstraction

Objects in JavaScript

Objects are the building blocks of JavaScript OOP. An object is a collection of key-value pairs, where values can be properties or functions (methods).


const person = {
  name: "John",
  age: 30,
  greet: function() {
    console.log("Hello, my name is " + this.name);
  }
};

person.greet();

Accessing Object Properties


console.log(person.name);
console.log(person["age"]);

Constructor Functions in JavaScript

Before ES6 classes, constructor functions were used to create multiple objects with similar properties.


function Person(name, age) {
  this.name = name;
  this.age = age;
}

const user1 = new Person("Alice", 25);
const user2 = new Person("Bob", 28);

console.log(user1.name);

ES6 Classes in JavaScript

ES6 introduced classes, making Object-Oriented JavaScript more structured and readable.


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

  greet() {
    console.log("Hello " + this.name);
  }
}

const user = new Person("David", 35);
user.greet();

Encapsulation in JavaScript

Encapsulation is the process of wrapping data and methods into a single unit and restricting direct access to some components.


class BankAccount {
  #balance = 0;

  deposit(amount) {
    this.#balance += amount;
  }

  getBalance() {
    return this.#balance;
  }
}

const account = new BankAccount();
account.deposit(500);
console.log(account.getBalance());

Inheritance in JavaScript

Inheritance allows one class to inherit properties and methods from another class, promoting code reuse.


class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(this.name + " makes a noise.");
  }
}

class Dog extends Animal {
  speak() {
    console.log(this.name + " barks.");
  }
}

const dog = new Dog("Rex");
dog.speak();

Polymorphism in JavaScript

Polymorphism allows methods to behave differently based on the object calling them.


class Shape {
  draw() {
    console.log("Drawing shape");
  }
}

class Circle extends Shape {
  draw() {
    console.log("Drawing circle");
  }
}

class Square extends Shape {
  draw() {
    console.log("Drawing square");
  }
}

const shapes = [new Circle(), new Square()];
shapes.forEach(shape => shape.draw());

Abstraction in JavaScript

Abstraction hides implementation details and shows only essential features.


class Car {
  startEngine() {
    this.#ignite();
    console.log("Engine started");
  }

  #ignite() {
    console.log("Ignition process...");
  }
}

const car = new Car();
car.startEngine();

Prototypal Inheritance in JavaScript

JavaScript uses prototypal inheritance instead of classical inheritance. Every object has a prototype, allowing it to inherit properties and methods.


function Animal(name) {
  this.name = name;
}

Animal.prototype.speak = function() {
  console.log(this.name + " makes a sound");
};

const cat = new Animal("Kitty");
cat.speak();

The Prototype Chain

The prototype chain is used to resolve property lookups. If a property is not found in an object, JavaScript looks up the prototype chain.


console.log(cat.toString());

Static Methods in JavaScript

Static methods belong to the class rather than instances of the class.


class MathUtils {
  static add(a, b) {
    return a + b;
  }
}

console.log(MathUtils.add(5, 3));

Getters and Setters

Getters and setters allow controlled access to object properties.


class User {
  constructor(name) {
    this._name = name;
  }

  get name() {
    return this._name;
  }

  set name(value) {
    this._name = value;
  }
}

const userObj = new User("Sam");
console.log(userObj.name);

Object.create() Method

Object.create() is used to create a new object with a specified prototype.


const animal = {
  speak() {
    console.log("Animal speaks");
  }
};

const dogObj = Object.create(animal);
dogObj.speak();

Composition vs Inheritance

Composition involves combining objects to achieve functionality, while inheritance relies on class hierarchy.


const canEat = {
  eat() {
    console.log("Eating...");
  }
};

const canWalk = {
  walk() {
    console.log("Walking...");
  }
};

const personObj = Object.assign({}, canEat, canWalk);
personObj.eat();
personObj.walk();

Object-Oriented JavaScript is a fundamental concept for modern developers. By understanding objects, classes, prototypes, and OOP principles, developers can build efficient and scalable applications. Mastering JavaScript OOP concepts ensures better code structure and maintainability, which is essential in real-world development.

Beginner 5 Hours

Object-Oriented JavaScript (OOP in JavaScript)

Introduction to Object-Oriented JavaScript

Object-Oriented JavaScript (OOP in JavaScript) is a powerful programming paradigm that allows developers to structure code using objects, classes, and reusable components. JavaScript, being a prototype-based language, provides flexible ways to implement object-oriented programming concepts such as encapsulation, inheritance, abstraction, and polymorphism.

In modern web development, understanding Object-Oriented JavaScript is essential for building scalable, maintainable, and reusable applications. Whether you are working on frontend frameworks or backend development using Node.js, mastering OOP concepts helps in writing clean and efficient code.

What is Object-Oriented Programming (OOP)?

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects. Objects contain properties (data) and methods (functions). OOP helps organize code into reusable structures, improving readability and maintainability.

Core Principles of OOP

  • Encapsulation
  • Inheritance
  • Polymorphism
  • Abstraction

Objects in JavaScript

Objects are the building blocks of JavaScript OOP. An object is a collection of key-value pairs, where values can be properties or functions (methods).

const person = { name: "John", age: 30, greet: function() { console.log("Hello, my name is " + this.name); } }; person.greet();

Accessing Object Properties

console.log(person.name); console.log(person["age"]);

Constructor Functions in JavaScript

Before ES6 classes, constructor functions were used to create multiple objects with similar properties.

function Person(name, age) { this.name = name; this.age = age; } const user1 = new Person("Alice", 25); const user2 = new Person("Bob", 28); console.log(user1.name);

ES6 Classes in JavaScript

ES6 introduced classes, making Object-Oriented JavaScript more structured and readable.

class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { console.log("Hello " + this.name); } } const user = new Person("David", 35); user.greet();

Encapsulation in JavaScript

Encapsulation is the process of wrapping data and methods into a single unit and restricting direct access to some components.

class BankAccount { #balance = 0; deposit(amount) { this.#balance += amount; } getBalance() { return this.#balance; } } const account = new BankAccount(); account.deposit(500); console.log(account.getBalance());

Inheritance in JavaScript

Inheritance allows one class to inherit properties and methods from another class, promoting code reuse.

class Animal { constructor(name) { this.name = name; } speak() { console.log(this.name + " makes a noise."); } } class Dog extends Animal { speak() { console.log(this.name + " barks."); } } const dog = new Dog("Rex"); dog.speak();

Polymorphism in JavaScript

Polymorphism allows methods to behave differently based on the object calling them.

class Shape { draw() { console.log("Drawing shape"); } } class Circle extends Shape { draw() { console.log("Drawing circle"); } } class Square extends Shape { draw() { console.log("Drawing square"); } } const shapes = [new Circle(), new Square()]; shapes.forEach(shape => shape.draw());

Abstraction in JavaScript

Abstraction hides implementation details and shows only essential features.

class Car { startEngine() { this.#ignite(); console.log("Engine started"); } #ignite() { console.log("Ignition process..."); } } const car = new Car(); car.startEngine();

Prototypal Inheritance in JavaScript

JavaScript uses prototypal inheritance instead of classical inheritance. Every object has a prototype, allowing it to inherit properties and methods.

function Animal(name) { this.name = name; } Animal.prototype.speak = function() { console.log(this.name + " makes a sound"); }; const cat = new Animal("Kitty"); cat.speak();

The Prototype Chain

The prototype chain is used to resolve property lookups. If a property is not found in an object, JavaScript looks up the prototype chain.

console.log(cat.toString());

Static Methods in JavaScript

Static methods belong to the class rather than instances of the class.

class MathUtils { static add(a, b) { return a + b; } } console.log(MathUtils.add(5, 3));

Getters and Setters

Getters and setters allow controlled access to object properties.

class User { constructor(name) { this._name = name; } get name() { return this._name; } set name(value) { this._name = value; } } const userObj = new User("Sam"); console.log(userObj.name);

Object.create() Method

Object.create() is used to create a new object with a specified prototype.

const animal = { speak() { console.log("Animal speaks"); } }; const dogObj = Object.create(animal); dogObj.speak();

Composition vs Inheritance

Composition involves combining objects to achieve functionality, while inheritance relies on class hierarchy.

const canEat = { eat() { console.log("Eating..."); } }; const canWalk = { walk() { console.log("Walking..."); } }; const personObj = Object.assign({}, canEat, canWalk); personObj.eat(); personObj.walk();

Object-Oriented JavaScript is a fundamental concept for modern developers. By understanding objects, classes, prototypes, and OOP principles, developers can build efficient and scalable applications. Mastering JavaScript OOP concepts ensures better code structure and maintainability, which is essential in real-world development.

Related Tutorials

Frequently Asked Questions for Node.js

A function passed as an argument and executed later.

Runs multiple instances to utilize multi-core systems.

Reusable blocks of code, exported and imported using require() or import.

nextTick() executes before setImmediate() in the event loop.

Starts a server and listens on specified port.

Node Package Manager β€” installs, manages, and shares JavaScript packages.

A minimal and flexible web application framework for Node.js.

A stream handles reading or writing data continuously.

It processes asynchronous callbacks and non-blocking I/O operations efficiently.

Node.js is a JavaScript runtime built on Chrome's V8 engine for server-side scripting.

An object representing the eventual completion or failure of an asynchronous operation.

require is CommonJS; import is ES6 syntax (requires transpilation or newer versions).

Use module.exports or exports.functionName.

Variables stored outside the code for configuration, accessed using process.env.


MongoDB, often used with Mongoose for schema management.

Describes project details and manages dependencies and scripts.

Synchronous blocks execution; asynchronous runs in background without blocking.

Allows or restricts resources shared between different origins.

Use try-catch, error events, or middleware for error handling.

Provides file system-related operations like read, write, delete.

Using event-driven architecture and non-blocking I/O.

Functions in Express that execute during request-response cycle.

A set of routes or endpoints to interact with server logic or databases.

Yes, it's single-threaded but handles concurrency using the event loop and asynchronous callbacks.

Middleware to parse incoming request bodies, like JSON or form data.

line

Copyrights © 2024 letsupdateskills All rights reserved