Table of Contents
Back Button
Back to Chapter
Control Statements
No items found.
Function & Events
No items found.
Array and its Types
No items found.
OOP : Object Oriented Programming
No items found.
Javascript Standards
No items found.
HTML DOM
No items found.
Javascript : Advanced 1
No items found.
Javascript : Advanced 2
No items found.
Additional JavaScript
No items found.

Prototypes

In the Previous Sections, you have learned after declaring constructor, new properties and methods cannot be added again.

To Overcome This Issue, Prototypes are Introduced.

All Javascript Objects inherit Properties and Methods from Prototypes.

So, You can now add properties and methods to Constructor By using Prototypes.

Syntax

To Declare New Property:

function constructorName(){ // constructorVariables } constructorName.prototype.newProperty = newValue;

To Declare New Method:

function constructorName(){ // constructorVariables } constructorName.prototype.methodName= function(){ //Statements }

Example

function home(homeName,homeSize,homeColour){ this.name = homeName; this.size = homeSize; this.colour = homeColour; } home.prototype.noOfRooms = 6; // Declaring Property home.prototype.getDetails = function(){ // Declaring Method return "Hello!!! Welcome to " + this.name + " Home, it is "+ this.size + " large and has " + this.noOfRooms + " Rooms of "+ this.colour + " Colour."; } var ramHome = new home("Ram's", "500 sq. ft.","blue"); console.log(ramHome.getDetails()); // Output // Hello!!! Welcome to Ram's Home, it is 500 sq. ft. large and has 6 Rooms of blue Colour.

Here,

We have declared property noOfRooms and method getDetails

Do You Know???

You can change the Methods and Properties or Pre-Defined Objects like Date, Array

How,

  1. Date objects inherit properties and methods from Date.prototype
  2. Array objects inherit properties and methods from Array.prototype

So, If you change the Array.prototype you can actually Change the Standard JS Objects.

Only modify your own prototypes. Never modify the prototypes of Standard JavaScript objects.

Ask queries
Contact Us on Whatsapp
Hi, How Can We Help You?