Skip to content
Related Articles

Related Articles

Prototypal Inheritance using __proto__ in JavaScript
  • Last Updated : 02 Jun, 2020

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :