JavaScript Inheritance & Prototypes
Understand JavaScript's prototypal inheritance.

1. The Prototype Chain

JavaScript objects have a link to a prototype object. When trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on.

JavaScript Code
Live JavaScript representation with highlighted changes
const parent = {
value: 2,
method() {
return this.value + 1;
}
};
const child = {
__proto__: parent
};
console.log(child.method()); // What does this log?
child.value = 4;
console.log(child.method()); // What about now?

2. Constructors and Prototypes

Constructor functions automatically set the [[Prototype]] for every object they create.

JavaScript Code
Live JavaScript representation with highlighted changes
function Box(value) {
this.value = value;
}
Box.prototype.getValue = function() {
return this.value;
};
const box = new Box(1);
console.log(box.getValue());
Console Output