Prototypes
const animal = {
speak() {
return 'generic sound';
},
};
const dog = Object.create(animal);
dog.speak(); // 'generic sound' — found on the prototype
dog has no speak of its own, yet the call works. Every object carries a hidden link to another object, and when you read a property that is not on the object itself, JavaScript follows that link — and then the next one — until it finds the property or reaches null. That chain is the prototype chain.
Functions get a prototype property, and objects made with new Fn() set their
prototype to Fn.prototype. That is how methods are shared instead of copied
onto every instance.
function Dog(name) {
this.name = name;
}
Dog.prototype.speak = function () {
return `${this.name} barks`;
};
Object.getPrototypeOf(obj) reads the link; obj.hasOwnProperty(key) tells you
whether a property is the object's own rather than inherited. Almost everything
ultimately inherits from Object.prototype, which is why toString works on
nearly every value.
You are about to answer a short quiz on the prototype chain.