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 JavaScript objects—the empty object {}. Every object created using the literal notation or a constructor inherits all properties and methods of an instance of the empty object.
We can verify it by trying to call the toString()
method:
var...