JavaScript Object Prototypes
JavaScript Basics

JavaScript Object Prototypes

Object prototype

JavaScript Object Prototypes Explained

JavaScript objects derive their properties and methods from a prototype. This concept is central to the prototype-based inheritance model of JavaScript.

Prototype Basics

When constructing objects using a function, each object instance is linked to the function's prototype property. This linkage allows all instances to share properties and methods defined on the prototype.

Example: Using Constructors to Create Objects

Example: Using Constructors to Create Objects
function Person(firstName, lastName, age, eyeColor) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
  this.eyeColor = eyeColor;
}

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

Modifying Constructors

Directly adding properties to the constructor function affects only new instances, not the prototype:

function Person(firstName, lastName, age, eyeColor) 
{  this.firstName = firstName;  this.lastName = lastName;  this.age = age;  this.eyeColor = eyeColor;  this.nationality = "English"; // Adds a nationality property directly to instances}

Prototype Inheritance

All JavaScript objects inherit from a prototype. For example:

  • Date objects inherit from Date.prototype.
  • Array objects inherit from Array.prototype.
  • Person objects inherit from Person.prototype.

The top of the prototype chain is Object.prototype, from which all objects inherit common methods like hasOwnProperty.

Adding Properties and Methods via Prototype

To extend the functionality of all instances of a constructor, you can add new properties or methods to the constructor's prototype. This is more memory efficient than defining methods directly in the constructor because the prototype's properties are shared among all instances.

Adding Properties Using Prototype

Person.prototype.nationality = "English"; // Adds a nationality property to all instances

Adding Methods Using Prototype

Person.prototype.fullName = function() {  return this.firstName + " " + this.lastName;}; // Adds a method to all instances‍

Best Practices with Prototypes

  • Modifications: Only modify your own custom prototypes. Avoid changing the prototypes of standard JavaScript objects like Array or Date, as such modifications can lead to unpredictable results in other parts of your code or in third-party libraries.
  • Performance: Using prototypes is efficient in terms of memory because shared properties and methods are not duplicated across instances.

Using the prototype effectively allows you to both extend functionality and maintain performance, by ensuring that all instances of a constructor share the same set of properties and methods.

Take a look into your desired course