🧬

How Prototypes Work in JavaScript

JavaScriptAdvanced

Understand prototype-based inheritance.

Code Example

JavaScript
// Every object has a prototype
const obj = {};
console.log(obj.__proto__); // Object prototype

// Constructor function
function Person(name) {
  this.name = name;
}

Person.prototype.greet = function() {
  console.log(`Hello, I'm ${this.name}`);
};

const alice = new Person("Alice");
alice.greet(); // "Hello, I'm Alice"

// Prototype chain
console.log(alice.hasOwnProperty("name")); // true
console.log(alice.hasOwnProperty("greet")); // false
console.log(alice.greet === Person.prototype.greet); // true

// Adding methods to built-in prototypes
Array.prototype.last = function() {
  return this[this.length - 1];
};

const arr = [1, 2, 3];
console.log(arr.last()); // 3

// Object.create
const animal = {
  type: "animal",
  speak() {
    console.log(`${this.type} makes a sound`);
  }
};

const dog = Object.create(animal);
dog.type = "dog";
dog.speak(); // "dog makes a sound"

// Prototype inheritance
function Animal(name) {
  this.name = name;
}

Animal.prototype.eat = function() {
  console.log(`${this.name} is eating`);
};

function Dog(name, breed) {
  Animal.call(this, name);
  this.breed = breed;
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.bark = function() {
  console.log("Woof!");
};

const rex = new Dog("Rex", "German Shepherd");
rex.eat(); // "Rex is eating"
rex.bark(); // "Woof!"

// ES6 class syntax (same thing)
class Cat {
  constructor(name) {
    this.name = name;
  }
  
  meow() {
    console.log("Meow!");
  }
}

const whiskers = new Cat("Whiskers");
whiskers.meow();

Explanation

Every object has __proto__. Constructor functions add methods to .prototype. Object.create() for inheritance. ES6 classes are syntactic sugar over prototypes.

Related Tutorials