Object Prototypes
JavaScript Object Prototypes
Section titled “JavaScript Object Prototypes”Every JavaScript object has a link to another object called its prototype. This prototype object has its own prototype, and so on, forming a prototype chain.
When you try to access a property or method on an object, JavaScript will first look on the object itself. If not found, it will look on its prototype, then the prototype’s prototype, and so on, until the property is found or the chain ends with null.
This mechanism is known as prototypal inheritance and is fundamental to how JavaScript objects inherit features.
Understanding Prototypes
Section titled “Understanding Prototypes”Objects created using an object literal ({}) or with new Object() inherit from Object.prototype.
Objects created with a constructor function (e.g., new Date()) inherit from the constructor’s prototype property (e.g., Date.prototype).
Object.prototype is at the top of the prototype chain for most objects. It provides common methods like toString(), hasOwnProperty(), etc.
Creating Objects with Constructor Functions
Section titled “Creating Objects with Constructor Functions”A common way to create objects that share a prototype is by using a constructor function:
// Constructor function for Person objectsfunction Person(first, last, age, eyeColor) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eyeColor;}
// Adding a method to the Person prototypePerson.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`;};With a constructor function, you use the new keyword to create new objects (instances). These instances will inherit from Person.prototype:
const myFather = new Person("John", "Doe", 50, "blue");const myMother = new Person("Sally", "Rally", 48, "green");
console.log(myFather.getFullName()); // Output: John Doeconsole.log(myMother.getFullName()); // Output: Sally RallyMethods added to the constructor’s prototype property are shared among all instances, making it memory efficient. |
|---|
ES6 Classes: Syntactic Sugar
Section titled “ES6 Classes: Syntactic Sugar”ES6 introduced the class syntax, which provides a cleaner and more familiar way (for developers from class-based languages) to create objects and manage inheritance. Under the hood, JavaScript classes still use prototypal inheritance.
Here’s the Person example using class syntax:
class Person { constructor(first, last, age, eyeColor) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eyeColor; }
getFullName() { return `${this.firstName} ${this.lastName}`; }
// Static property (belongs to the class, not instances) static species = "Homo sapiens";}
const myFriend = new Person("Alex", "Smith", 30, "brown");console.log(myFriend.getFullName()); // Output: Alex Smithconsole.log(Person.species); // Output: Homo sapiensAdding Properties/Methods to Individual Objects
Section titled “Adding Properties/Methods to Individual Objects”You can add properties or methods directly to an individual object instance. These will only exist on that specific object.
myFather.nationality = "English"; // Property added only to myFatherconsole.log(myFather.nationality); // Output: English// console.log(myMother.nationality); // Output: undefined
myMother.greet = function() { // Method added only to myMother return `Hello, I am ${this.getFullName()}`;};console.log(myMother.greet()); // Output: Hello, I am Sally Rally// myFather.greet(); // This would cause an errorModifying Prototypes (Use with Caution)
Section titled “Modifying Prototypes (Use with Caution)”You can add new properties and methods to an existing constructor’s prototype property. This will make them available to all existing and future instances of that constructor (unless an instance has its own property with the same name).
// Adding a new method to ALL Person instances via the prototypePerson.prototype.getAgeInYears = function() { return `${this.age} years old`;};
console.log(myFather.getAgeInYears()); // Output: 50 years oldconsole.log(myMother.getAgeInYears()); // Output: 48 years oldImportant: Only modify prototypes that you have defined. Never modify the prototypes of standard built-in JavaScript objects like Object.prototype, Array.prototype, etc. This is considered bad practice as it can lead to unpredictable behavior and conflicts with other code or future JavaScript versions. |
|---|