Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

JavaScript | Object Prototypes

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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:


My Personal Notes arrow_drop_up
Last Updated : 01 Mar, 2019
Like Article
Save Article
Similar Reads
Related Tutorials