What are JavaScript prototypes and what are they for?

Question:

I would like to know what are JavaScript prototypes and how can I use them or if there is any kind of benefit.

Answer:

As a first note, JavaScript OOP is based on prototypes and not classes. To see more information about prototype-based OOP vrs. class-based OOP you can visit the following link (in English).

Prototypes are a set of standards for integrating Object Oriented Programming into JavaScript . So, following these rules we must be able to create the different Object Oriented methodologies:

  • Inheritance
  • Encapsulation
  • Abstraction
  • Polymorphism

Of course, not all methodologies are available.

How can I use prototypes?

ECMAScript 5

To create a class:

function Polygon(height, width){
  this.height = height;
  this.width = width;
}

To inherit over a base class:

function Square(side){
  this.prototype = Object.create(Polygon.prototype);
  Polygon.call(this, side, side);

  this.getArea = function(){
    return this.height * this.width;
  }
}

ECMAScript 6

To create a class:

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

To inherit from a base class:

class Square extends Polygon {
  constructor(side) {
    super(side, side);
  }
  getArea() {
    return this.height * this.width;
  }
}

With this we can create an instance with:

var square = new Square(5);
// debe imprimir 25
console.log(square.getArea());

Examples taken from Inheritance and the prototype chain .

Profits

  • Have high-level programming.
  • Have different ways of creating objects.
  • Have inheritance in properties and methods.
  • Basically the benefits of having prototypes in JavaScript is the possibility of using Object Oriented Programming as a Software methodology.
Scroll to Top