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
✔ 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
✔ 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
✔ 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! š