Java Script is a powerful programming language that plays a major role in web development. it enables developers to create interactive and dynamic web pages, making it an important part of web development. One of the most confusing topic related to Java Script that confuses beginners but it is essential to learn for mastering the language is prototypes.
In this blog, we will delve into the concept of prototypes in JavaScript covering all the topics related to prototypes and by the end of the blog, you will have a solid understanding of prototypes in JavaScript and how to leverage them in code to create more robust and maintainable applications.
What is a Prototype in JavaScript?
Definition of Prototype
Explanation of Prototype Chain
Examples of Prototypes in JavaScript
Let's look at some examples to understand prototypes and the prototype chain better.
Example 1: Basic Object Prototype
let animal = {
eats: true,
walk() {
console.log("Animal walks");
}
};
let rabbit = {
jumps: true
};
// Setting rabbit's prototype to animal
rabbit.__proto__ = animal;
console.log(rabbit.eats); // true
rabbit.walk(); // Animal walks(code-box)
In this example:
animal
is an object with a propertyeats
and a methodwalk
.rabbit
is an object with a propertyjumps
.- By setting
rabbit.__proto__ = animal
, we makeanimal
the prototype ofrabbit
. - As a result,
rabbit
can access the properties and methods ofanimal
through the prototype chain.
Example 2: Function Prototype
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}`);
};
let john = new Person("John");
john.sayHello(); // Hello, my name is John(code-box)
In this example:
Person
is a constructor function.- We add a method
sayHello
toPerson.prototype
. - When we create a new instance
john
usingnew Person("John")
, it inherits thesayHello
method fromPerson.prototype
.
Example 3: Class Prototype (ES6)
class Car {
constructor(model) {
this.model = model;
}
drive() {
console.log(`${this.model} is driving`);
}
}
let tesla = new Car("Tesla Model S");
tesla.drive(); // Tesla Model S is driving(code-box)
In this example:
Car
is a class with a constructor method and adrive
method.- Instances of
Car
, such astesla
, inherit thedrive
method from theCar
prototype.
Why use Prototypes in JavaScript?
Benefits of using Prototypes
1. Memory Efficiency
Like In this example 2 shown above,
sayHello
is defined on Person.prototype
, so all instances of Person
share the same method, avoiding redundancy and saving memory.2. Shared Methods Among Instances
function Car(model) {this.model = model;}Car.prototype.drive = function() {console.log(`${this.model} is driving`);};let car1 = new Car("Tesla");let car2 = new Car("BMW");car1.drive(); // Tesla is drivingcar2.drive(); // BMW is driving(code-box)
Both car1
and car2
share the drive
method, which is defined on the prototype, ensuring that any change to drive
will be reflected across all instances.
How Prototypes Work in JavaScript?
The __proto__
Property
The prototype
Property of Functions
__proto__
property is set to the constructor function's prototype
object, enabling inheritance of properties and methods.How Objects Inherit Properties and Methods
__proto__
). This process continues up the prototype chain until the property or method is found or the end of the chain is reached (null
).Example Demonstrating Inheritance Through Prototypes
// Constructor function for Userfunction User(username) {this.username = username;}// Adding a method to the prototype of UserUser.prototype.login = function() {console.log(`${this.username} has logged in.`);};// Creating instances of Userlet adminUser = new User("adminUser");let regularUser = new User("regularUser");// Using the shared methodadminUser.login(); // adminUser has logged in.regularUser.login(); // regularUser has logged in.// Checking prototypesconsole.log(adminUser.__proto__ === User.prototype); // trueconsole.log(regularUser.__proto__ === User.prototype); // true(code-box)
In this example:
User
is a constructor function for general user accounts.- The
login
method is added toUser.prototype
, making it available to all instances ofUser
.
Real-World Example with ES6 Class and Inheritance
PremiumUser
class that inherits from the User
class.// Base class for Userclass User {constructor(username) {this.username = username;}}// Adding the login method to the prototype of UserUser.prototype.login = function() {console.log(`${this.username} has logged in.`);};// Derived class for PremiumUserclass PremiumUser extends User {constructor(username) {super(username); // Call the parent class constructor}accessPremiumContent() {console.log(`${this.username} is accessing premium content.`);}}// Creating instances of PremiumUserlet premiumUser1 = new PremiumUser("premiumUser1");let premiumUser2 = new PremiumUser("premiumUser2");// Using inherited and own methodspremiumUser1.login(); // premiumUser1 has logged in.premiumUser1.accessPremiumContent(); // premiumUser1 is accessing premium content.premiumUser2.login(); // premiumUser2 has logged in.premiumUser2.accessPremiumContent(); // premiumUser2 is accessing premium content.// Checking prototypesconsole.log(premiumUser1.__proto__ === PremiumUser.prototype); // trueconsole.log(premiumUser1.__proto__.__proto__ === User.prototype); // true(code-box)
In this example:
User
is the base class for user accounts with alogin
method.PremiumUser
extendsUser
and adds an additional method,accessPremiumContent
.PremiumUser
inherits thelogin
method fromUser
, and also has its own methodaccessPremiumContent
.- The prototype chain shows that
premiumUser1.__proto__
isPremiumUser.prototype
, andPremiumUser.prototype.__proto__
isUser.prototype
.