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");
We also know that new properties cannot be added to an object with an existing constructor:
Example
Person.nationality = "English";
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"; }
Prototype inheritance
All JavaScript objects inherit properties and methods from a prototype object:
Date
Objects inherits from theDate.prototype
.Array
Objects inherits from theArray.prototype
.Person
Objects inherits from thePerson.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.
Date
Objects, Array
objects, and Person
objects from the Object.prototype
inheritance.
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";
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;
};