JavaScript Prototype (original) (raw)

Last Updated : 14 Feb, 2025

In JavaScript, everything is an object, including functions, arrays, and strings, which are specialized types of objects. JavaScript follows a prototype-based system, where objects inherit properties and methods from other objects through prototypes. This prototype mechanism plays a key role in how JavaScript handles inheritance and object relationships.

What is Prototype in JavaScript?

In JavaScript, the prototype is a container for methods and properties. When methods or properties are added to the prototype of a function, array, or string, they become shared by all instances of that particular object type. Prototype in general can be understood as a mould and all its instances can be considered as the car made from it.

JavaScript `

Object.prototype.print = function () { console.log('I am from object prototype') } let b = { name: 'Pranjal', age: 21 } b.print()

`

Output

I am from object prototype

How Prototype Works in JavaScript?

Creating Constructor Functions

A constructor function in JavaScript is a special function used to create and initialize objects, typically using the new keyword. It sets up properties and methods on the newly created object, allowing for the creation of multiple instances with shared behavior.

JavaScript ``

function Person(name) { this.name = name; } Person.prototype.sayHello = function () { console.log(Hello, my name is ${this.name}.); }; const n = new Person("Sheema"); n.sayHello();

``

Output

Hello, my name is Sheema.

Adding method to prototype

This code defines a sum method on the Array.prototype to calculate the sum of all elements in an array. It then calls this method on two different arrays, arr and arr2, and logs the results.

JavaScript `

let a1 = [1, 2, 3, 4, 5] let a2 = [5, 6, 7, 8, 9] Array.prototype.sum = function () { let sum = 0 for (let i = 0; i < this.length; i++) { sum += this[i] } return sum } console.log(a1.sum()) console.log(a2.sum())

`

Prototype Inheritance

This code demonstrates prototype inheritance where the child constructor inherits from the parent constructor, allowing instances of child to access methods defined in parent's prototype. It also adds a custom caste method in the child prototype.

JavaScript ``

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

Animal.prototype.speak = function () { console.log(${this.name} makes a noise.); };

function Dog(name) { Animal.call(this, name); // Call the parent constructor }

Dog.prototype = Object.create(Animal.prototype); // Set up inheritance Dog.prototype.constructor = Dog;

Dog.prototype.speak = function () { console.log(${this.name} barks.); };

const dog = new Dog('Rex'); dog.speak(); // Rex barks.

``

Advanced Prototype Use Cases

1. Extending Built-in Objects

In JavaScript, you can extend built-in objects like Array, String, etc., by adding custom methods to their prototypes. This allows you to add new functionality to these objects without modifying the original class.

JavaScript `

Array.prototype.first = function () { return this[0]; };

const n = [10, 20, 30, 40]; console.log(n.first());

`

2. Shared Methods for Performance Optimization

To optimize performance in JavaScript, shared methods are added to prototypes, allowing multiple instances of objects to access the same method without duplicating it for each instance. This reduces memory usage and improves efficiency.

JavaScript ``

function Person(name, age) { this.name = name; this.age = age; }

Person.prototype.introduce = function () { return Hello, my name is <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>t</mi><mi>h</mi><mi>i</mi><mi>s</mi><mi mathvariant="normal">.</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi></mrow><mi>a</mi><mi>n</mi><mi>d</mi><mi>I</mi><mi>a</mi><mi>m</mi></mrow><annotation encoding="application/x-tex">{this.name} and I am </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="mord mathnormal">hi</span><span class="mord mathnormal">s</span><span class="mord">.</span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span></span><span class="mord mathnormal">an</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.07847em;">I</span><span class="mord mathnormal">am</span></span></span></span>{this.age} years old.; };

const person1 = new Person('Pranjal', 25); const person2 = new Person('Ayaan', 30);

console.log(person1.introduce()); console.log(person2.introduce());

``

Output

Hello, my name is Pranjal and I am 25 years old. Hello, my name is Ayaan and I am 30 years old.

3. Dynamic Method Assignment

In JavaScript, dynamic method assignment allows you to add or modify methods on objects or prototypes at runtime. This provides flexibility, enabling you to change or extend functionality dynamically as the program runs.

JavaScript ``

function Person(name, age) { this.name = name; this.age = age; }

const person1 = new Person('Pranshi', 25); person1.introduce = function () { return Hi, I am <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>t</mi><mi>h</mi><mi>i</mi><mi>s</mi><mi mathvariant="normal">.</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi></mrow><mi>a</mi><mi>n</mi><mi>d</mi><mi>I</mi><mi>a</mi><mi>m</mi></mrow><annotation encoding="application/x-tex">{this.name} and I am </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="mord mathnormal">hi</span><span class="mord mathnormal">s</span><span class="mord">.</span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span></span><span class="mord mathnormal">an</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.07847em;">I</span><span class="mord mathnormal">am</span></span></span></span>{this.age} years old.; };

console.log(person1.introduce());

``

Output

Hi, I am Pranshi and I am 25 years old.

Advantages of Prototypes

Prototype chain in JavaScript

In JavaScript, functions, arrays, and strings are all considered types of objects. They are just specialized forms of the general object type. The Object type acts as the parent or base for these different object types. All the other object type's like array's, functions and Strings are connected as a child to the Object through prototype.

JavaScript `

let o = { name: "Pranjal", age: 21 } let a = [1, 2, 3, 4, 5] let s = "Hello GFG" function p() { console.log('My name is xyzabc') } Object.prototype.common = function () { console.log('I am a shared method from prototype') } o.common() a.common() s.common() p.common()

`

Output

I am a shared method from prototype I am a shared method from prototype I am a shared method from prototype I am a shared method from prototype

Js-Prototypes

To understand more follow the article on prototype chain

Conclusion

JavaScript prototypes are key to inheritance, code reuse, and memory efficiency. They allow methods to be shared across instances, reducing redundancy and improving performance. Prototypes provide flexibility to extend or modify objects dynamically. Understanding them is essential for mastering JavaScript and creating efficient, maintainable applications.