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:
To Declare New Method:
Example
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,
- Date objects inherit properties and methods from Date.prototype
- 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.