Skip to main content

Object-Oriented JavaScript

Prototypes Demystified

0:00
LearnStep 1/3

Understanding JavaScript Prototypes

The Prototype Chain

In JavaScript, every object has a hidden internal property called [[Prototype]]. When you try to access a property that doesn't exist on an object, JavaScript automatically looks at that object's prototype. If it's not there, it looks at the prototype's prototype, and so on. This is called the prototype chain.

javascript

Object.getPrototypeOf and Object.setPrototypeOf

While many environments support the __proto__ property, the modern and standard way to interact with an object's prototype is through Object.getPrototypeOf(obj) and Object.setPrototypeOf(obj, proto).

javascript

Creating Objects with Object.create

Object.create(proto) is a powerful method that creates a new object and sets its prototype to the provided proto object. This allows for a more direct form of inheritance than using constructor functions.

javascript

Prototype Debugging

When debugging, use console.dir(obj) in the browser console to inspect the [[Prototype]] property (often labeled as <prototype> or __proto__). Remember that the chain ends at Object.prototype, whose prototype is null.