Objects and prototypes

Until now, we have seen two ways to create objects in JavaScript. The first and simplest approach is based on the literal notation:

var person = {name: "John", surname: "Smith"}; 

The second and more flexible approach is based on a constructor function:

function Person(name, surname) { 
  this.name = name; 
  this.surname = surname; 
} 
 
var person = new Person("John", "Smith"); 

There is no difference between the resulting objects of both approaches. Our feeling in both cases is that we have created two new objects from scratch. Actually, it is not true. In both cases, we created a derived object—an object derived from an instance of the built-in Object() constructor. It is a constructor that allows us to create a base object of all ...

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.