JavaScript Prototype
All JavaScript objects inherit properties and methods from a prototype.
In previous sections, we learned how to use the constructor of an object:
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 new properties cannot be added to an existing constructor:
Example
Person.nationality = "English";
To add a new property, it 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";
}
Prototype Inheritance
All JavaScript objects inherit properties and methods from a prototype:
Date
objects inherit fromDate.prototype
.Array
objects inherit fromArray.prototype
.Person
objects inherit fromPerson.prototype
.
All objects in JavaScript are instances of Object, which sits at the top of the prototype chain.
JavaScript objects have a link to a prototype object. When trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached.
Date
objects, Array
objects, and Person
objects inherit from Object.prototype
.
Adding Properties and Methods
Sometimes we want to add new properties or methods to all existing objects of a given type.
Other times we want to add properties or methods to an object constructor.
The prototype property allows us to add new properties to an object constructor:
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
We can also use the prototype property to add new methods to an object 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;
};