Object Prototypes in JavaScript
Object Prototypes in JavaScript
What is a Prototype?
Every JavaScript object has an internal link to another object called its prototype.
The prototype object provides inherited properties and methods to the original object.
This is the core of JavaScript’s prototype-based inheritance system.
How Prototypes Work
When you access a property or method on an object, JavaScript first looks on the object itself.
If it doesn’t find it, it looks up the prototype chain until it finds the property or reaches
null.The prototype chain allows sharing behavior among multiple objects.
Accessing Prototype
Use
Object.getPrototypeOf(obj)to get the prototype of an object.
const obj = {};console.log(Object.getPrototypeOf(obj) === Object.prototype); // trueSetting Prototype
Use
Object.create(proto)to create a new object with a specified prototype.
const animal = { speak() { console.log("Animal sound"); }};const dog = Object.create(animal);dog.speak(); // Animal soundConstructor Functions and Prototypes
Functions have a property
prototype.When using
new, the created object’s prototype is set to the function’sprototype.
function Person(name) { this.name = name;}Person.prototype.greet = function() { console.log("Hello, " + this.name);};const alice = new Person("Alice");alice.greet(); // Hello, AliceES6 Classes Use Prototypes Underneath
class Person { constructor(name) { this.name = name; } greet() { console.log("Hello, " + this.name); }}const bob = new Person("Bob");bob.greet(); // Hello, BobThis works by adding methods to Person.prototype.
Prototype Chain Example
const animal = { eats: true };const rabbit = Object.create(animal);rabbit.jumps = true;console.log(rabbit.jumps); // trueconsole.log(rabbit.eats); // true (from prototype)Summary
| Concept | Description |
|---|---|
| Prototype | Object linked internally to provide inheritance |
| Prototype Chain | Chain of prototypes looked up for properties |
prototype Property | Holds shared methods for constructor functions |
Object.create() | Creates object with specific prototype |
Want examples on modifying prototypes or prototype pitfalls?