#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
•Question 9 of 50hard

What are Prototypes in JavaScript?

Understanding prototypal inheritance.

What You'll Learn

  • What prototypes are
  • Prototype chain
  • Prototypal inheritance

What is a Prototype?

Every JavaScript object has an internal link to another object called its prototype. Objects inherit properties and methods from their prototype.

Prototype Chain

code.jsJavaScript
const arr = [1, 2, 3];

// arr → Array.prototype → Object.prototype → null
console.log(arr.__proto__ === Array.prototype); // true
console.log(Array.prototype.__proto__ === Object.prototype); // true

Creating Objects with Prototypes

code.jsJavaScript
function Animal(name) {
  this.name = name;
}

Animal.prototype.speak = function() {
  console.log(this.name + ' makes a sound');
};

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

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

Dog.prototype.bark = function() {
  console.log(this.name + ' barks');
};

const dog = new Dog('Rex');
dog.speak(); // 'Rex makes a sound'
dog.bark();  // 'Rex barks'

Modern Class Syntax

code.jsJavaScript
class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(this.name + ' makes a sound');
  }
}

class Dog extends Animal {
  bark() {
    console.log(this.name + ' barks');
  }
}