Constructor and Prototype

 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, eye) {

  this.firstName = first;

  this.lastName = last;

  this.age = age;

  this.eyeColor = eye;

}


Person.nationality = "English";


const myFather = new Person("John", "Doe", 50, "blue");

const myMother = new Person("Sally", "Rally", 48, "green");

console.log(myFather);


console.log(myMother);

console.log(myFather.nationality); // undefinedd

..............To add a new property to a constructor, you must add it to the constructor function:

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

  this.firstName = first;

  this.lastName = last;

  this.age = age;

  this.eyeColor = eye;

  this.nationality = "English";

}


const myFather = new Person("John", "Doe", 50, "blue");

const myMother = new Person("Sally", "Rally", 48, "green");

console.log(myFather.nationality); // english

Adding Properties and Methods to Objects

Sometimes you want to add new properties (or methods) to all existing objects of a given type.

Sometimes you want to add new properties (or methods) to an object constructor.

All JavaScript objects inherit properties and methods from a prototype:

  • Date objects inherit from Date.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.

Using the prototype Property

The JavaScript prototype property allows you to add new properties to object constructors:

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

  this.firstName = first;

  this.lastName = last;

  this.age = age;

  this.eyeColor = eye;

}


Person.prototype.nationality = "English";

const myFather = new Person("John", "Doe", 50, "blue");

const myMother = new Person("Sally", "Rally", 48, "green");

console.log(myFather.nationality); //English

console.log(myMother.nationality); //English

The JavaScript prototype property also allows you to add new methods to objects constructors:

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;

};

const myFather = new Person("John", "Doe", 50, "blue");


console.log(myFather.name()); 

Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence