Understanding “Prototypes” in JavaScript

Object

In JavaScript, objects are pairs of keys and values. For example, I wanted to describe my name, I could have an object with two keys:

firstName would point to “Erdal” and lastName would point to “Satık”. Keys in a JavaScript object are Strings.

To create new object in JavaScript;

var person = Object.create(null); // this creates an empty objects

Prototypes

JavaScript objects also have one additional attribute: a pointer to another object. We call this pointer the object’s prototype. If you try to look up a key on an object and it is not found, JavaScript will look for it in the prototype. It will follow the “prototype chain” until it sees a nullvalue. In that case, it returns undefined

So, shortly about protoypes;

  • Every JavaScript object has a prototype. The prototype is also an object.

  • All JavaScript objects inherit their properties and methods from their prototype.

  • Objects created using an object literal, or with new Object(), inherit from a prototype called Object.prototype.

  • Objects created with new Date() inherit the Date.prototype.

  • All JavaScript objects (Date, Array, RegExp, Function, ….) inherit from the Object.prototype.

Creating Prototype

The standard way to create an object prototype is to use an object constructor function:

The constructor function is the prototype for Person objects.

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

new keyword to create new objects from the same prototype:

var myFather = new Person("John", "Doe", 50, "blue"); var myMother = new Person("Sally", "Rally", 48, "green"); Adding a Property to an Object — Using the prototype Property

myFather.nationality = "Turkish";

Adding a Method to an Object

myFather.name = function () { return this.firstName + " " + this.lastName; };

Using the prototype Property

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