Tuesday, June 12, 2018

JavaScript Object Prototypes

All JavaScript objects inherit properties and methods from a prototype.
in the previous chapter we learned how to use an object constructor.
function Person( first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyecolor  = color;
}
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

Prototype Inheritance
All JavaScript objects inherit properties and methods from a prototype.
Date objects inherit from Data.prototype. Array objects inherit from Array.prototype. Person objects inherit from Person.prototype. The Object.prototype is on the top of the prototype inheritance chain:
Date objects, Array objects, and Person objects inherit from Object.prototype.

Adding Properties and Methods to Objects
Somtimes you want ot add new proerties (or methods) to all existing objcts 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 Person( first, last, age, eyecolor)
{
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyecolor = color;
}
Person.prototype.nationality = "English";

No comments:

Post a Comment