Member-only story
In JavaScript, inheriting from built-in objects can be a powerful technique to extend functionality and create custom objects tailored to your needs.
In this guide, we’ll delve into the process of inheriting from built-in objects, understand its benefits, and provide clear examples to help you implement this technique effectively.
Understanding Inheritance from Built-in Objects
In JavaScript, built-in objects like Array
, String
, and Object
can serve as prototypes for custom objects. Inheriting from these objects allows you to leverage their existing functionality while adding custom features specific to your application.
Inheriting from Arrays
Let’s start by inheriting from the Array
object to create a custom object:
function CustomArray() {
Array.call(this); // Call the Array constructor with 'this' context
}
CustomArray.prototype = Object.create(Array.prototype);
CustomArray.prototype.constructor = CustomArray;
const customArray = new CustomArray();
customArray.push(1, 2, 3);
console.log(customArray.length); //…