JavaScript | Object Prototypes
JavaScript prototypes are used to accessing properties and methods of objects. Inherited properties are originally defined in the prototype or parent object. The Date object is inherited from Date.prototype, Array object inherits from Array.prototype etc. The prototypes may be used to add new properties and methods to the existing objects and object constructor.
Syntax:
Object.prototype
Example 1: This example adding new property to the object.
<!DOCTYPE html> < html > < head > < title > JavaScript Object Prototypes </ title > </ head > < body > < h1 >GeeksforGeeks</ h1 > < h2 >JavaScript Object Prototypes</ h2 > < p id = "GFG" ></ p > < script > function Student(a, b) { this.name = a; this.id = b; } Student.prototype.age = 12; var s1 = new Student("Dinesh", 1234567); document.getElementById("GFG").innerHTML = s1.name + " is " + s1.age + " years old."; </ script > </ body > </ html > |
Output:
Example 2: This example adding new method to the object.
<!DOCTYPE html> < html > < head > < title > JavaScript Object Prototypes </ title > </ head > < body > < h1 >GeeksforGeeks</ h1 > < h2 >JavaScript Object Prototypes</ h2 > < p id = "GFG" ></ p > <!-- Script to add new method --> < script > function Student(a, b) { this.name = a; this.id = b; } Student.prototype.details = function() { return this.name + " " + this.id }; var s1 = new Student("Dinesh", 1234567); document.getElementById("GFG").innerHTML = s1.details(); </ script > </ body > </ html > |
Output:
Please Login to comment...