Open In App

Prototypal Inheritance using __proto__ in JavaScript

Last Updated : 02 Jun, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
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. html
<!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

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy