Thursday, September 4, 2025
HomeLanguagesJavascriptPrototypal Inheritance using __proto__ in JavaScript

Prototypal Inheritance using __proto__ in JavaScript

Every object with its methods and properties contains an internal and hidden property known as [[Prototype]]. The Prototypal Inheritance is a feature in javascript used to add methods and properties in objects. It is a method by which an object can inherit the properties and methods of another object. Traditionally, in order to get and set the [[Prototype]] of an object, we use Object.getPrototypeOf and Object.setPrototypeOf. Nowadays, in modern language, it is being set using __proto__.

Syntax:

ChildObject.__proto__ = ParentObject

Example In the given example, there are two objects ‘person’ and ‘GFGuser’. The object ‘GFGuser’ inherits the methods and properties of the object ‘person’ and further uses them.




<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>prototype</title>
    </head>
    <body>
        <script>
            // object person
            let person = {
                talk: true,
                Canfly() {
                    return "Sorry, Can't fly";
                },
            };
            // Object GFGuser
            let GFGuser = {
                CanCode: true,
                CanCook() {
                    return "Can't say";
                },
                
              //  Inheriting the properties and methods of person
                __proto__: person, 
            };
  
            // Printing on console
            // Property of person
            console.log("Can a GFG User talk: " + GFGuser.talk); 
            
            // Method of person
            console.log("Can a GFG User fly: " + GFGuser.Canfly()); 
            
            // Property of GFGuser
            console.log("Can a GFG User code: " + GFGuser.CanCode); 
            
            // Method of GFGuser
            console.log("Can a GFG User cook: " + GFGuser.CanCook()); 
        </script>
    </body>
</html>


Output

RELATED ARTICLES

Most Popular

Dominic
32263 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6627 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11858 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6696 POSTS0 COMMENTS
Umr Jansen
6716 POSTS0 COMMENTS