Javascript - Object-Oriented JavaScript

Object-Oriented JavaScript

Object-Oriented JavaScript

JavaScript supports object-oriented programming (OOP), though its approach differs from classical OOP languages like Java or C++. With features such as prototypes and classes, JavaScript enables the creation of complex, reusable objects.

Prototypes

Every JavaScript object has a prototype. A prototype is an object from which other objects inherit properties and methods. This prototype-based inheritance allows code sharing across instances.

Example: Using Prototypes

// Create a constructor function
function Person(name, age) {
  this.name = name;
  this.age = age;
}

// Add a method to the prototype
Person.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};

// Create an instance of Person
const alice = new Person('Alice', 30);
alice.greet(); // Output: Hello, my name is Alice and I am 30 years old.

The constructor sets up a blueprint for Person objects. The greet method is added to the prototype, meaning all instances of Person share it, promoting memory efficiency and code reuse.

Classes

ES6 introduced the class syntax, which provides a cleaner and more familiar structure for object-oriented code. Behind the scenes, classes still use prototypes.

Example: Defining and Using a Class

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

  // Method defined in the class
  greet() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

// Create an instance of the class
const bob = new Person('Bob', 25);
bob.greet(); // Output: Hello, my name is Bob and I am 25 years old.

The class keyword defines the structure. The constructor initializes properties, and methods like greet are automatically placed on the prototype for sharing across instances.

Inheritance with Classes

JavaScript classes support inheritance using the extends keyword, allowing you to create subclasses that inherit and extend functionality from parent classes.

Example: Class Inheritance

// Define a parent class
class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

// Define a subclass that extends Animal
class Dog extends Animal {
  constructor(name, breed) {
    super(name); // Call the parent class constructor
    this.breed = breed;
  }

  // Override the speak method
  speak() {
    console.log(`${this.name} the ${this.breed} barks.`);
  }
}

// Create an instance of the subclass
const charlie = new Dog('Charlie', 'Labrador');
charlie.speak(); // Output: Charlie the Labrador barks.

The Dog class extends Animal, gaining access to its constructor and methods. The speak method is overridden to implement custom behavior for Dog instances.

Beginner 5 Hours
Object-Oriented JavaScript

Object-Oriented JavaScript

JavaScript supports object-oriented programming (OOP), though its approach differs from classical OOP languages like Java or C++. With features such as prototypes and classes, JavaScript enables the creation of complex, reusable objects.

Prototypes

Every JavaScript object has a prototype. A prototype is an object from which other objects inherit properties and methods. This prototype-based inheritance allows code sharing across instances.

Example: Using Prototypes

// Create a constructor function function Person(name, age) { this.name = name; this.age = age; } // Add a method to the prototype Person.prototype.greet = function() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); }; // Create an instance of Person const alice = new Person('Alice', 30); alice.greet(); // Output: Hello, my name is Alice and I am 30 years old.

The constructor sets up a blueprint for Person objects. The greet method is added to the prototype, meaning all instances of Person share it, promoting memory efficiency and code reuse.

Classes

ES6 introduced the class syntax, which provides a cleaner and more familiar structure for object-oriented code. Behind the scenes, classes still use prototypes.

Example: Defining and Using a Class

// Define a class class Person { constructor(name, age) { this.name = name; this.age = age; } // Method defined in the class greet() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); } } // Create an instance of the class const bob = new Person('Bob', 25); bob.greet(); // Output: Hello, my name is Bob and I am 25 years old.

The class keyword defines the structure. The constructor initializes properties, and methods like greet are automatically placed on the prototype for sharing across instances.

Inheritance with Classes

JavaScript classes support inheritance using the extends keyword, allowing you to create subclasses that inherit and extend functionality from parent classes.

Example: Class Inheritance

// Define a parent class class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a noise.`); } } // Define a subclass that extends Animal class Dog extends Animal { constructor(name, breed) { super(name); // Call the parent class constructor this.breed = breed; } // Override the speak method speak() { console.log(`${this.name} the ${this.breed} barks.`); } } // Create an instance of the subclass const charlie = new Dog('Charlie', 'Labrador'); charlie.speak(); // Output: Charlie the Labrador barks.

The Dog class extends Animal, gaining access to its constructor and methods. The speak method is overridden to implement custom behavior for Dog instances.

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