BugCast
JS JavaScript

Prototypes & Inheritance in JavaScript

Prototype chain, class syntax, and the questions that separate mid from senior developers.

BugCast Admin··7 min read

Prototype Chain

Every object has an internal [[Prototype]] link. When you access a property, JavaScript walks up the chain until it finds it or returns undefined.

const animal = { eats: true };
const rabbit = Object.create(animal);
rabbit.jumps = true;

console.log(rabbit.eats); // true — inherited from animal

Classes Are Syntactic Sugar

class User {
  constructor(name) {
    this.name = name;
  }
  greet() {
    return `Hello, ${this.name}`;
  }
}

Under the hood, methods live on User.prototype.

Interview Questions

Q: Difference between proto and prototype?

  • prototype exists on functions (used when called with new)
  • __proto__ / Object.getPrototypeOf is the object's link to its prototype

Q: How does new work?

  1. Creates empty object
  2. Sets prototype to constructor.prototype
  3. Runs constructor with this bound to object
  4. Returns object (unless constructor returns an object)

Q: Implement inheritance without class

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

function Dog(name) {
  Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
#prototypes#oop#interview

Related posts