WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript Object Prototypes


All JavaScript objects inherit properties and methods from a prototype. In previous chapters we learned how to use the constructor of an object:

Creating a Prototype

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");
We also know that it is not possible to add new attributes to an existing object constructor:

Example

Person.nationality = "English";
Try it Yourself »

To add a new property you need to add it in the constructor:

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

prototype inheritance

All JavaScript objects inherit properties and methods from a prototype:

    The
  • Date object inherits from Date.prototype .
  • Array objects inherit from Array.prototype .
  • Person objects inherit from Person.prototype .

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

JavaScript objects have a chain that points 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, and searches upwards one by one until it finds a property with a matching name or reaches the prototype. The end of the chain.

The

Date object, Array object, and Person object inherit from Object.prototype .

Add attributes and methods

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

Also, 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 Yourself »

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 Yourself »