Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Object Prototypes

All JavaScript objects inherit properties and methods from a prototype.

In the previous chapter, we learned how to use an object constructor.

Example

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

const myFather = new Person(“John”“Doe”50“blue”);
const myMother = new Person(“Sally”“Rally”48“green”);

We also learned that you cannot add a new property to an existing object constructor.

Example

Person.nationality = “English”;

To add a new property to a constructor, you must define it within 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 from Date.prototype
  • Array objects inherit from Array.prototype
  • Person objects inherit from Person.prototype

At the top of the prototype inheritance chain is Object.prototype, which is inherited by Date, Array, and Person objects.

Adding Properties and Methods to Objects

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

Other times, you might want to add new properties (or methods) directly to an object constructor.

Using the prototype Property

The JavaScript prototype property lets you add new properties to object constructors.

Example

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

Person.prototype.nationality = “English”;

The JavaScript prototype property also enables you to add new methods to object constructors.

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;
};