What Are Prototypes in JavaScript? Why Are They Important?

What Are Prototypes in JavaScript? Why Are They Important?

The Issue

If you've worked with object-oriented programming languages before, the class syntax is the clearest way to declare a new object. JavaScript is also considered an object-oriented programming language, but if you're an early JavaScript developer from around a decade ago, it didn't have the class syntax. Instead, it supported inheritance through prototypes, which had a somewhat different syntax compared to OOP in most other languages and wasn't highly regarded for its powerful OOP features.

In recent years, ES6 introduced the class keyword to make it easier for developers to write OOP-style code or, in other words, make it more friendly for those accustomed to the OOP syntax. However, at its core, it's still powered by prototypes. In this article, we'll explore what prototypes are and why they are important in JavaScript.

What Are Prototypes?

Prototypes are the mechanism by which JavaScript objects inherit features from one another. Every object created from a constructor function has a default prototype, which is the prototype of that constructor function.

Every object in JavaScript has properties and methods integrated into it, called the prototype. The prototype itself is also an object, so it has its own prototype, creating a prototype chain. This chain only ends when the prototype is null.

Prototypes define the properties and methods that objects created from that constructor function can access. When an object is created, it inherits all properties and methods from the prototype of the constructor function.

For example:

const myObject = {
  name: "2coffee",
  greet() {
    console.log(`Greetings from ${this.name}`);
  },
};

myObject.greet(); // Greetings from 2coffee

In the example above, greet() is a method of myObject, so it can call that method. However, besides greet(), myObject is an Object, so it inherits the entire prototype of Object. The prototypes within myObject would look something like this:

__defineGetter__
__defineSetter__
__lookupGetter__
__lookupSetter__
__proto__
name
constructor
greet
hasOwnProperty
isPrototypeOf
propertyIsEnumerable
toLocaleString
toString
valueOf

myObject has access to all of these prototypes, such as calling the toString method.

myObject.toString(); // "[object Object]"

When trying to access a property of an object, if the property isn't found within the object itself, it will look for it in the prototype of the parent object. This continues until the property is found or the prototype chain ends, returning undefined.

For example, with a Date object in JavaScript. Date is an instance of Object, and Date also has its own prototype, so an object created from Date will have at least 3 layers of prototypes.

banner

What Are Prototypes Used For?

As mentioned earlier, prototypes are primarily used for inheritance in object-oriented programming. Using prototypes in JavaScript allows us to efficiently add properties and methods to objects. Instead of creating methods and properties for each object, we can add them to the prototype of the constructor function, allowing all objects created from that constructor function to access them.

For example, consider a program that defines a Geometry class with two methods: calculatePerimeter and calculateArea. Two classes, Square and Circle, inherit from Geometry through prototypes, written as follows:

// Define the Geometry class
function Geometry() {}

// Method to calculate perimeter
Geometry.prototype.calculatePerimeter = function() { return; }

// Method to calculate area
Geometry.prototype.calculateArea = function() { return; }

// Define the Square class inheriting from Geometry
function Square(sideLength) {
  this.sideLength = sideLength;
}

Square.prototype = Object.create(Geometry.prototype);
Square.prototype.constructor = Square;

// Override the calculatePerimeter method for Square
Square.prototype.calculatePerimeter = function() {
  return this.sideLength * 4;
}

// Override the calculateArea method for Square
Square.prototype.calculateArea = function() {
  return this.sideLength * this.sideLength;
}

// Define the Circle class inheriting from Geometry
function Circle(radius) {
  this.radius = radius;
}

Circle.prototype = Object.create(Geometry.prototype);
Circle.prototype.constructor = Circle;

// Override the calculatePerimeter method for Circle
Circle.prototype.calculatePerimeter = function() {
  return 2 * Math.PI * this.radius;
}

// Override the calculateArea method for Circle
Circle.prototype.calculateArea = function() {
  return Math.PI * this.radius * this.radius;
}

Prototypes and Classes

Since ES6, JavaScript introduced a new syntax for inheritance, the class keyword. By using this new syntax, it makes us more familiar with object-oriented programming syntax from other languages.

For example, the same program as above but written using classes looks much cleaner:

// Define the Geometry class
class Geometry {
  calculatePerimeter() { return; }

  calculateArea() { return; }
}

// Define the Square class inheriting from Geometry
class Square extends Geometry {
  constructor(sideLength) {
    super();
    this.sideLength = sideLength;
  }

  calculatePerimeter() {
    return this.sideLength * 4;
  }

  calculateArea() {
    return this.sideLength * this.sideLength;
  }
}

// Define the Circle class inheriting from Geometry
class Circle extends Geometry {
  constructor(radius) {
    super();
    this.radius = radius;
  }

  calculatePerimeter() {
    return 2 * Math.PI * this.radius;
  }

  calculateArea() {
    return Math.PI * this.radius * this.radius;
  }
}

Even though class was introduced in ES6, it still has some limitations compared to OOP in pure object-oriented languages like Java and C#. Partly because class is still based on prototypes, but it was created to simplify code complexity, making it more readable and concise.

The Importance of Prototypes

Prototypes are a crucial concept in JavaScript because they allow us to create objects with inheritance and reuse code efficiently.

Objects created from the same constructor function can share properties and methods defined in the prototype of that constructor function. This reduces code duplication and saves memory for your application.

If you look closely, you'll notice that almost everything in JavaScript is rooted in prototypes. Creating a new object, it inherits the entire prototype from Object. Creating a function, it inherits the entire prototype from Function, and so on.

banner

Additionally, using prototypes allows us to create child objects that inherit properties and methods from parent objects. This enhances code reusability, minimizes duplication, and improves maintenance of your application.

Furthermore, prototypes provide a way to extend existing objects in JavaScript. By adding properties and methods to an object's prototype, we can expand the functionality of that object without modifying the original source code.

Therefore, prototypes are a fundamental concept in JavaScript and one of the ways to increase flexibility, efficiency, and maintainability in the long run.

Conclusion

Prototypes are the mechanism by which JavaScript objects inherit features from one another. Early JavaScript developers had to write inheritance based on prototypes. In recent years, ES6 introduced the class syntax, making it friendlier for those accustomed to object-oriented programming syntax. Prototypes are a fundamental concept in JavaScript, as nearly everything, such as Object, Function, and more, is built on prototypes. Understanding the essence of prototypes will help you learn more advanced concepts in the future.

References:

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.
Author

Hello, my name is Hoai - a developer who tells stories through writing ✍️ and creating products 🚀. With many years of programming experience, I have contributed to various products that bring value to users at my workplace as well as to myself. My hobbies include reading, writing, and researching... I created this blog with the mission of delivering quality articles to the readers of 2coffee.dev.Follow me through these channels LinkedIn, Facebook, Instagram, Telegram.

Did you find this article helpful?
NoYes

Comments (0)