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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>                    

chevron_right


Output:

Example 2: This example adding new method to the object.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>                    

chevron_right


Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.