Skip to content
Jing Lu edited this page May 23, 2013 · 24 revisions

All the properties belonging to an object will be available to another object, if the object is the prototype of the latter.

object A         object B
  +- a: 10         +- prototype: object A

A.a == 10         // true
B.a == 10         // true

The property a does not exist in B, but it is also available to B since A is prototype of B. Code for example:

var arr = new Array();
arr.push(1);              // in fact 'push' does not belong to 'arr', it is method of Array.prototype
console.log(arr);

The result is:

[1]

All constructors (functions) like Array has a property named 'prototype', that is the prototype of Array.

Since arr is instance of Array so the properties belonging to Array.prototype will be all available to arr. For example:

var arr = new Array();
arr.push(1);

Array.prototype.add = function(element) {
  this.push(element);
};

arr.add(2);
console.log(arr);

The output is:

[1, 2]

Clone this wiki locally