What Are Prototypes in JavaScript? Why Are They Important?

What Are Prototypes in JavaScript? Why Are They Important?

Daily short news for you
  • Continuing to update on the lawsuit between the Deno group and Oracle over the name JavaScript: It seems that Deno is at a disadvantage as the court has dismissed the Deno group's complaint. However, in August, they (Oracle) must be held accountable for each reason, acknowledging or denying the allegations presented by the Deno group in the lawsuit.

    JavaScript™ Trademark Update

    » Read more
  • This time last year, I was probably busy running. This year, I'm overwhelmed with work and have lost interest. But sitting too much has made my belly grow, getting all bloated and gaining weight. Well, I’ll just try to walk every day to relax my muscles and mind a bit 😮‍💨

    The goal is over 8k steps 👌

    » Read more
  • Just a small change on the Node.js homepage has stirred the community. Specifically, when you visit the homepage nodejs.org, you will see a button "Get security support for Node.js 18 and below" right below the "Download" button. What’s notable is that it leads to an external website outside of Node.js, discussing a service that provides security solutions for older Node.js versions, which no longer receive security updates. It even stands out more than the Download button.

    The community has condemned this action, stating that it feels a bit "excessive," and suggested consulting them before making such decisions. On the Node side, they argue that this is appropriate as it is from a very significant sponsoring partner. As of now, the link still exists. Let's wait to see what happens next.

    » Read more

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.

Prototypes in Date object

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.

Prototype of an object

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:

Premium
Hello

5 profound lessons

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

View all

Subscribe to receive new article notifications

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

Comments (0)

Leave a comment...