Prototypes

Overview

Prototypes are how JavaScript provides inheritance. See the Inheritance page for good articles on Inheritance and Prototypes in JavaScript.

Functions that are Constructors (because they are called with the new keyword) Properties Prototype (this is nothing more or less than an Object)   Instances (of an object because it was created with new)
function Pet(weight, fullname) {
 //create the instance variables
 this.weight = weight;
 this.fullname = fullname;
 console.log(' ');
 }

‑‑‑ .prototype ‑‑‑>

<‑‑‑ .constructor ‑‑‑

{

constructor: Pet,

eat: function(),

makeNoise: function(),

who: function()

}

  var salamander = new Pet();
   

↑ Cat is sub-classed from Pet ↑

Because we did: Cat.prototype = new Pet;

Cat.prototype.constructor = Cat;

   
function Cat(weight, breed, fullname) {
 Pet.call(this, weight, fullname);
 this.breed = breed;
 }

‑‑‑ .prototype ‑‑‑>

<‑‑‑ .constructor ‑‑‑

 

{

constructor: Cat,

purr: function()

}

 

var maria = new Cat();

Prototype is a property of functions, not objects. Therefore Cat.prototype is valid (returns an Object), but maria.prototype is not (returns undefined). If you want the prototype of an instance (like maria) then you need to use one of these three ways:

W3C standard (fails in IE<=8 and Opera):

Object.getPrototypeOf(maria);

Non-standard (but supported by most browsers except IE):

maria.__proto__;

Fallback (but only if constructor.prototype has not been replaced and fails with Object.create)

maria.constructor.prototype;

Full Example

Look at the source code for this page, and inspect the console, to fully understand what is going on.