Ads Top

What is the prototype in javascript

How to use prototype in javascript?
We use of prototype in the object when we call any function to another function Or using anywhere and you have required that new property adding so how it possible because you are calling this function from another resource. Yes, it’s possible through to Prototype. 

<script>
 
function f1(){
            this.name = 'Sheo';
        }
     
        f1.prototype.email = 'sheo@gmail.com';
        f1.prototype = Object.create(f1.prototype);

  var rrr = new f1();
        console.log(rrr.name);
        console.log(rrr.email);
</script>

Described above example: You have f1 an object and you will get “name” property easily in the new object. But if you want to add new property “email” then you can write as “f1.prototype.email” and assign a value as you want. When you want to access this property then you will write reference object name where you want to add and create a new object as this “f1.prototype = Object.create(f1.prototype);
“Important that you can modify only added new property through prototype not already added property of the object”
And now you can access the newly added property.

How to access an object to another object?

It’s required to use “call” method, already defined in the Javascript. 
<script>
        function f1(){
            this.name = 'Sheo';
        }
      
        function f2(){
            f1.call(this);
            this.lastName = 'Sagar';
        }
       
        var rrr = new f2();
        console.log(rrr.name);
        console.log(rrr.lastName);
    </script>
You can use the call method as given above example. “f1.call(this)
It's called all property of the “f1” object. You can see another example of the prototype inheritance.
<script>
        function f1(){
            this.name = 'Sheo';
        }
        f1.prototype.email = 'sheo@gmail.com';

        function f2(){
            f1.call(this);
            this.lastName = 'Sagar';
        }
        f2.prototype = Object.create(f1.prototype);
        f2.prototype.dob = '18-03-2008';

        function f3(){
            f2.call(this);
            this.name = 'Raghav';
        }
        f3.prototype = Object.create(f2.prototype);

        var rrr = new f1();
        console.log(rrr.name);
        console.log(rrr.email);
       
        var sss = new f3();
        console.log(sss.name);
        console.log(sss.email);
        console.log(sss.dob);
        console.log(sss.lastName);
    </script>

No comments:

Copyright Reserved to Anything Learn. Powered by Blogger.