Skip to content

Prototype

Spicy — senior dev territoryFrontend

ELI5 — The Vibe Check

Every object in JavaScript secretly has a parent object called its prototype. When you look for a property on an object and it's not there, JavaScript looks at the prototype, then the prototype's prototype, all the way up. This is the prototype chain — how JavaScript does inheritance. Modern classes are just fancy syntax on top of this.

Real Talk

The prototype is an object from which other objects inherit properties and methods via the prototype chain. Every JavaScript object has an internal [[Prototype]] link (accessible via Object.getPrototypeOf() or proto). ES6 class syntax is syntactic sugar over prototype-based inheritance — classes don't change the underlying prototype mechanism.

Show Me The Code

function Animal(name) {
  this.name = name
}

Animal.prototype.speak = function() {
  return `${this.name} makes a noise.`
}

const dog = new Animal('Rex')
console.log(dog.speak()) // 'Rex makes a noise.'
console.log(dog.hasOwnProperty('name'))  // true
console.log(dog.hasOwnProperty('speak')) // false (it's on prototype)

When You'll Hear This

Adding methods to Array.prototype is possible but considered bad practice.,ES6 classes compile down to prototype-based code in older environments.,The prototype chain ends at Object.prototype, whose prototype is null.

Made with passive-aggressive love by manoga.digital. Powered by Claude.