Object prototypes

The flexibility of JavaScript objects is expressed primarily through the possibility of changing their structure even after their creation. Even while using a constructor to create an object, we continue to have this possibility. For example, you can write the following code:

var johnSmith = new Person("John", "Smith"); 
var marioRossi = new Person("Mario", "Rossi"); 
 
johnSmith.greets = function() { 
  console.log("Hello " + this.name + " " + this.surname + "!"); 
}; 

This code will create a new method greets() for the johnSmith object without affecting the structure of marioRossi.

Basically, while creating objects, we can start from a common structure defined by a constructor and then customize it to our needs.

But how do we change the ...

Get Mastering JavaScript Object-Oriented Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.