Loading Please Wait...

Logo Lynxsia IT Solutions

JavaScript Object Prototypes

JS Object Prototypes

All JavaScript objects inherit properties and methods from a prototype.

Object Constructor

In the previous chapter we learned how to use an object constructor.

					 
        
          function Employee(name, email) {
            this.name = name;
            this.email = email;
          }

          const manager = new Employee("John Doe", "john@gmail.com");
          const receptionist = new Employee("Neelam Singh", "neelam@gmail.com");
        
      

We also learned that you can not add a new property to an existing object constructor.

					 
        
          Employee.ager= 35;
        
      

To add a new property to a constructor, you must add it to the constructor function.

					 
        
          function Employee(name, email) {
            this.name = name;
            this.email = email;
            this.age = 18;
          }
        
      
Prototype Inheritance

All JavaScript objects inherit properties and methods from a prototype:

  • Date objects inherit from Date.prototype
  • Array objects inherit from Array.prototype
  • Employee objects inherit from Employee.prototype

The Object.prototype is on the top of the prototype inheritance chain.

Date objects, Array objects, and Employee objects inherit from Object.prototype.

Adding Properties and Methods to Objects

Sometimes you want to add new properties (or methods) to all existing objects of a given type.

Sometimes you want to add new properties (or methods) to an object constructor.

Using the prototype Property

The JavaScript prototype property allows you to add new properties to object constructors.

					 
        
          function Employee(name, email) {
            this.name = name;
            this.email = email;
          }

          Employee.prototype.age = 18;
        
      

The JavaScript prototype property also allows you to add new methods to objects constructors.

					 
        
          function Employee(name, email) {
            this.name = name;
            this.email = email;
          }

          Employee.prototype.greeting = function() {
            return "Hello " + this.name;
          };
        
      
Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.

How you feel about this blog:

Share this blog on:

Report Us

If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com

Contact Us
Ads
Logo
Lynxsia IT Solutions

We are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..

Kotwali Road, Chhiptehri, Banda, 210001, UP, India

Copyright © 2022, Lynxsia IT Solutions, All rights reserved