SyntaxStudy
Sign Up
JavaScript Advanced 9 min read

The Prototype Chain

The Prototype Chain

Every JavaScript object has an internal link to another object called its prototype. When you access a property on an object, the engine first looks on the object itself; if not found, it walks up the prototype chain until it either finds the property or reaches null. This mechanism is the foundation of inheritance in JavaScript.

Object.getPrototypeOf()

Use Object.getPrototypeOf(obj) to inspect an object's prototype. The prototype of a plain object literal is Object.prototype, which provides methods like toString(), hasOwnProperty(), and valueOf().

Object.create(proto)

Object.create(proto) creates a new object whose prototype is proto. This is the lowest-level way to set up inheritance without using classes.

hasOwnProperty and in

obj.hasOwnProperty(key) returns true only if the property exists directly on the object, not on its prototype. The in operator checks the full chain.

Example
const animal = {
  breathe() { return this.name + ' breathes'; }
};
const dog = Object.create(animal);
dog.name = 'Rex';
dog.bark = function() { return 'Woof!'; };
console.log(dog.bark());    // Woof!
console.log(dog.breathe()); // Rex breathes (inherited)
console.log(dog.hasOwnProperty('bark'));    // true
console.log(dog.hasOwnProperty('breathe')); // false
console.log('breathe' in dog);             // true
console.log(Object.getPrototypeOf(dog) === animal); // true
Pro Tip

In modern JavaScript use classes or Object.create() for inheritance — avoid direct manipulation of __proto__, which is a legacy accessor that exists for compatibility reasons.