JavaScript objects inherit directly from other objects. Every object has a hidden link, [[Prototype]], and property lookups walk that chain until they find a match or hit null.
Lookup walks the chain
const animal = { eats: true, describe() { return `${this.name} eats: ${this.eats}`; } };
const rabbit = Object.create(animal);
rabbit.name = "Bunny";
rabbit.jumps = true;
console.log(rabbit.jumps, rabbit.eats, rabbit.describe());
console.log(Object.hasOwn(rabbit, "eats"), "eats" in rabbit);
console.log(Object.getPrototypeOf(rabbit) === animal);
console.log(Object.getPrototypeOf(animal) === Object.prototype);
console.log(Object.getPrototypeOf(Object.prototype));true true Bunny eats: true
false true
true
true
nullrabbit → animal → Object.prototype → null
Writes do not walk the chain
const proto = { greeting: "hello", list: [] };
const child = Object.create(proto);
child.greeting = "hi"; // creates an OWN property (shadowing)
child.list.push(1); // mutates the SHARED array on the prototype
console.log(child.greeting, proto.greeting, proto.list);hi hello [ 1 ]prototype vs [[Prototype]]
Two different things with confusingly similar names:
function Dog(name) { this.name = name; }
Dog.prototype.bark = function () { return `${this.name}: woof`; };
const rex = new Dog("Rex");
console.log(rex.bark());
console.log(Object.getPrototypeOf(rex) === Dog.prototype);
console.log(Dog.prototype.constructor === Dog, rex.constructor.name);
console.log(Object.hasOwn(rex, "bark"), rex instanceof Dog);Rex: woof
true
true Dog
false trueBuilt-in chains
const arr = [1, 2];
console.log(Object.getPrototypeOf(arr) === Array.prototype);
console.log(Object.getPrototypeOf(Array.prototype) === Object.prototype);
const fn = () => {};
console.log(Object.getPrototypeOf(fn) === Function.prototype);
console.log(arr.hasOwnProperty("length"), arr.hasOwnProperty("map"));true
true
true
true falseHow instanceof works
function myInstanceOf(obj, Ctor) {
let proto = Object.getPrototypeOf(obj);
while (proto !== null) {
if (proto === Ctor.prototype) return true;
proto = Object.getPrototypeOf(proto);
}
return false;
}
console.log(myInstanceOf([], Array), myInstanceOf([], Object), myInstanceOf([], Map));true true falseExplain prototypal inheritance.
What is the difference between __proto__ and prototype?