JavaScript Prototype


All JavaScript objects inherit properties and methods from a prototype object.

In the previous chapters we learned how to use the object constructor:

Example

function Person(first, last, age, eyecolor) {
   this.firstName = first;
   this.lastName = last;
   this.age = age;
   this.eyeColor = eyecolor;
}
 
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

Try It! 

We also know that new properties cannot be added to an object with an existing constructor:

Example

Person.nationality = "English";

Try It! 

To add a new attribute needs to be added in the constructor function:

Example

function Person(first, last, age, eyecolor) {
   this.firstName = first;
   this.lastName = last;
   this.age = age;
   this.eyeColor = eyecolor;
   this.nationality = "English";
}

Try It! 


Prototype inheritance

All JavaScript objects inherit properties and methods from a prototype object:

  • DateObjects inherits from the Date.prototype.

  • ArrayObjects inherits from the Array.prototype.

  • PersonObjects inherits from the Person.prototype.

All objects in JavaScript are instances of Object at the top of the prototype chain.

JavaScript objects have a link to a prototype object. When trying to access the properties of an object, it not only searches on the object, but also searches for the prototype of the object and the prototype of the object, searching upwards successively until it finds a property with a matching name or reaches the prototype The end of the chain.

DateObjects, Arrayobjects, and Personobjects from the Object.prototypeinheritance.

Add properties and methods

Sometimes we want to add new properties or methods to all existing objects.

In addition, sometimes we want to add properties or methods to the object's constructor.

Use the prototype property to add new properties to the object's constructor:

Example

function Person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
}
 
Person.prototype.nationality = "English";

 Try It! 

Of course, we can also use the prototype property to add new methods to the object's constructor:

Example

function Person(first, last, age, eyecolor) {

   this.firstName = first;

   this.lastName = last;

   this.age = age;

   this.eyeColor = eyecolor;

}

 

Person.prototype.name = function() {

   return this.firstName + "" + this.lastName;

};

Try It!