Extending Built-in Classes in JavaScript

Extending Built-in Classes in JavaScript

Extending Built-in Classes in JavaScript

In JavaScript, you can extend built-in classes (like Array, Error, Map, etc.) using class and extends. This allows you to add custom methods or modify behavior while still keeping the original functionality of the built-in class.

šŸ”¹ Extending the Array Class

By extending Array, we can create a custom array class with additional methods.

Example: Custom Array with Extra Methods

class CustomArray extends Array { sum() { return this.reduce((acc, num) => acc + num, 0); } } const numbers = new CustomArray(10, 20, 30); console.log(numbers.sum()); // ✅ Output: 60 console.log(numbers.length); // ✅ Output: 3 console.log(numbers instanceof Array); // ✅ Output: true

CustomArray behaves like a regular array but includes a sum() method.
✔ It still has all Array methods (push(), pop(), etc.).

šŸ”¹ Extending the Error Class

Custom error classes help differentiate types of errors.

Example: Custom Error Class

class ValidationError extends Error { constructor(message) { super(message); this.name = "ValidationError"; } } try { throw new ValidationError("Invalid input data!"); } catch (error) { console.log(error.name); // ✅ Output: ValidationError console.log(error.message); // ✅ Output: Invalid input data! console.log(error.stack); // ✅ Stack trace }

ValidationError extends Error, allowing custom error handling.

šŸ”¹ Extending Map to Add Custom Functionality

Extending Map allows us to modify its behavior or add new methods.

Example: Custom Map with Default Values

class DefaultMap extends Map { constructor(defaultValue) { super(); this.defaultValue = defaultValue; } get(key) { return this.has(key) ? super.get(key) : this.defaultValue; } } const settings = new DefaultMap("Not Set"); settings.set("theme", "dark"); console.log(settings.get("theme")); // ✅ Output: dark console.log(settings.get("fontSize")); // ✅ Output: Not Set

✔ The custom get() method ensures a default value if the key does not exist.

šŸ”¹ When to Use Built-in Class Inheritance?

✔ Creating specialized versions of built-in classes (e.g., CustomArray with sum()).
✔ Making error handling more descriptive (ValidationError, AuthError).
✔ Customizing data structures (e.g., DefaultMap).

šŸŽÆ Summary

✔ Use class YourClass extends BuiltInClass to extend built-in classes.
✔ Call super() in the constructor to inherit parent behavior.
✔ You can add new methods or override existing ones.

šŸš€ Need help with extending a specific class? Let me know! 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close