How does JavaScript .prototype work?

I'm not that into dynamic programming languages but I've written my fair share of JavaScript code. I never really got my head around this prototype-based programming, does any one know how this works?

var obj = new Object();
obj.prototype.test = function() { alert('Hello?'); };
var obj2 = new obj();

I remember a lot discussion I had with people a while back (I'm not exactly sure what I'm doing) but as I understand it, there's no concept of a class. It's just an object, and instances of those objects are clones of the original, right?

But what is the exact purpose of this ".prototype" property in JavaScript? How does it relate to instantiating objects?

Update: correct way

var obj = new Object(); // not a functional object
obj.prototype.test = function() { alert('Hello?'); }; // this is wrong!

function MyObject() {} // a first class functional object
MyObject.prototype.test = function() { alert('OK'); } // OK

Also these slides really helped a lot.



Every JavaScript object has an internal property called [[Prototype]]. If you look up a property via obj.propName or obj['propName'] and the object does not have such a property - which can be checked via obj.hasOwnProperty('propName') - the runtime looks up the property in the object referenced by [[Prototype]] instead. If the prototype-object also doesn't have such a property, its prototype is checked in turn, thus walking the original object's prototype-chain until a match is found or its end is reached.

Some JavaScript implementations allow direct access to the [[Prototype]] property, eg via a non-standard property named __proto__. In general, it's only possible to set an object's prototype during object creation: If you create a new object via new Func(), the object's [[Prototype]] property will be set to the object referenced by Func.prototype.

This allows to simulate classes in JavaScript, although JavaScript's inheritance system is - as we have seen - prototypical, and not class-based:

Just think of constructor functions as classes and the properties of the prototype (ie of the object referenced by the constructor function's prototype property) as shared members, ie members which are the same for each instance. In class-based systems, methods are implemented the same way for each instance, so methods are normally added to the prototype, whereas an object's fields are instance-specific and therefore added to the object itself during construction.


In a language implementing classical inheritance like Java, C# or C++ you start by creating a class--a blueprint for your objects--and then you can create new objects from that class or you can extend the class, defining a new class that augments the original class.

In JavaScript you first create an object (there is no concept of class), then you can augment your own object or create new objects from it. It's not difficult, but a little foreign and hard to metabolize for somebody used to the classical way.


//Define a functional object to hold persons in JavaScript
var Person = function(name) { = name;

//Add dynamically to the already defined object a new getter
Person.prototype.getName = function() {

//Create a new object of type Person
var john = new Person("John");

//Try the getter

//If now I modify person, also John gets the updates
Person.prototype.sayMyName = function() {
  alert('Hello, my name is ' + this.getName());

//Call the new method on john

Until now I've been extending the base object, now I create another object and then inheriting from Person.

//Create a new object of type Customer by defining its constructor. It's not 
//related to Person for now.
var Customer = function(name) { = name;

//Now I link the objects and to do so, we link the prototype of Customer to 
//a new instance of Person. The prototype is the base that will be used to 
//construct all new instances and also, will modify dynamically all already 
//constructed objects because in JavaScript objects retain a pointer to the 
Customer.prototype = new Person();     

//Now I can call the methods of Person on the Customer, let's try, first 
//I need to create a Customer.
var myCustomer = new Customer('Dream Inc.');

//If I add new methods to Person, they will be added to Customer, but if I
//add new methods to Customer they won't be added to Person. Example:
Customer.prototype.setAmountDue = function(amountDue) {
    this.amountDue = amountDue;
Customer.prototype.getAmountDue = function() {
    return this.amountDue;

//Let's try:       

var Person = function (name) { = name;
Person.prototype.getName = function () {
var john = new Person("John");
Person.prototype.sayMyName = function () {
    alert('Hello, my name is ' + this.getName());
var Customer = function (name) { = name;
Customer.prototype = new Person();

var myCustomer = new Customer('Dream Inc.');
Customer.prototype.setAmountDue = function (amountDue) {
    this.amountDue = amountDue;
Customer.prototype.getAmountDue = function () {
    return this.amountDue;

While as said I can't call setAmountDue(), getAmountDue() on a Person.

//The following statement generates an error.

This is a very simple prototype based object model that would be considered as a sample during the explanation, with no comment yet:

function Person(name){ = name;
Person.prototype.getName = function(){
var person = new Person("George");

There are some crucial points that we have to consider before going through the prototype concept.

1- How JavaScript functions actually work:

To take the first step we have to figure out, how JavaScript functions actually work , as a class like function using this keyword in it or just as a regular function with its arguments, what it does and what it returns.

Let's say we want to create a Person object model. but in this step I'm gonna be trying to do the same exact thing without using prototype and new keyword.

So in this step functions, objects and this keyword, are all we have.

The first question would be how this keyword could be useful without using new keyword.

So to answer that let's say we have an empty object, and two functions like:

var person = {};
function Person(name){ = name;  }

function getName(){

and now without using new keyword how we could use these functions. So JavaScript has 3 different ways to do that:

a. first way is just to call the function as a regular function:

getName();//would print the "George" in the console

in this case, this would be the current context object, which is usually is the global window object in the browser or GLOBAL in Node.js. It means we would have, in browser or in Node.js, with "George" as its value.

b. We can attach them to an object, as its properties

-The easiest way to do this is modifying the empty person object, like:

person.Person = Person;
person.getName = getName;

this way we can call them like:

person.getName();// -->"George"

and now the person object is like:

Object {Person: function, getName: function, name: "George"}

-The other way to attach a property to an object is using the prototype of that object that can be find in any JavaScript object with the name of __proto__, and I have tried to explain it a bit on the summary part. So we could get the similar result by doing:

person.__proto__.Person = Person;
person.__proto__.getName = getName;

But this way what we actually are doing is modifying the Object.prototype, because whenever we create a JavaScript object using literals ({ ... }), it gets created based on Object.prototype, which means it gets attached to the newly created object as an attribute named __proto__ , so if we change it, as we have done on our previous code snippet, all the JavaScript objects would get changed, not a good practice. So what could be the better practice now:

person.__proto__ = {
    Person: Person,
    getName: getName

and now other objects are in peace, but it still doesn't seem to be a good practice. So we have still one more solutions, but to use this solution we should get back to that line of code where person object got created (var person = {};) then change it like:

var propertiesObject = {
    Person: Person,
    getName: getName
var person = Object.create(propertiesObject);

what it does is creating a new JavaScript Object and attach the propertiesObject to the __proto__ attribute. So to make sure you can do:

console.log(person.__proto__===propertiesObject); //true

But the tricky point here is you have access to all the properties defined in __proto__ on the first level of the person object(read the summary part for more detail).

as you see using any of these two way this would exactly point to the person object.

c. JavaScript has another way to provide the function with this, which is using call or apply to invoke the function.

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).


The call() method calls a function with a given this value and arguments provided individually.

this way which is my favorite, we can easily call our functions like:, "George");


//apply is more useful when params count is not fixed
Person.apply(person, ["George"]);;   

these 3 methods are the important initial steps to figure out the .prototype functionality.

2- How does the new keyword works?

this is the second step to understand the .prototype functionality.this is what I use to simulate the process:

function Person(name){ = name;  }
my_person_prototype = { getName: function(){ console.log(; } };

in this part I'm gonna be trying to take all the steps which JavaScript takes, without using the new keyword and prototype, when you use new keyword. so when we do new Person("George"), Person function serves as a constructor, These are what JavaScript does, one by one:

a. first of all it makes an empty object, basically an empty hash like:

var newObject = {};

b. the next step that JavaScript takes is to attach the all prototype objects to the newly created object

we have my_person_prototype here similar to the prototype object.

for(var key in my_person_prototype){
    newObject[key] = my_person_prototype[key];

It is not the way that JavaScript actually attaches the properties that are defined in the prototype. The actual way is related to the prototype chain concept.

a. & b. Instead of these two steps you can have the exact same result by doing:

var newObject = Object.create(my_person_prototype);
//here you can check out the __proto__ attribute
console.log(newObject.__proto__ === my_person_prototype); //true
//and also check if you have access to your desired properties
console.log(typeof newObject.getName);//"function"

now we can call the getName function in our my_person_prototype:


c. then it gives that object to the constructor,

we can do this with our sample like:, "George");


Person.apply(newObject, ["George"]);

then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created.

now the end result before simulating the other steps: Object {name: "George"}


Basically, when you use the new keyword on a function, you are calling on that and that function serves as a constructor, so when you say:

new FunctionName()

JavaScript internally makes an object, an empty hash and then it gives that object to the constructor, then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created and then it gives you that object of course if you haven't used the return statement in your function or if you've put a return undefined; at the end of your function body.

So when JavaScript goes to look up a property on an object, the first thing it does, is it looks it up on that object. And then there is a secret property [[prototype]] which we usually have it like __proto__ and that property is what JavaScript looks at next. And when it looks through the __proto__, as far as it is again another JavaScript object, it has its own __proto__ attribute, it goes up and up until it gets to the point where the next __proto__ is null. The point is the only object in JavaScript that its __proto__ attribute is null is Object.prototype object:


and that's how inheritance works in JavaScript.

The prototype chain

In other words, when you have a prototype property on a function and you call a new on that, after JavaScript finishes looking at that newly created object for properties, it will go look at the function's .prototype and also it is possible that this object has its own internal prototype. and so on.


prototype allows you to make classes. if you do not use prototype then it becomes a static.

Here is a short example.

var obj = new Object();
obj.test = function() { alert('Hello?'); };

In the above case, you have static funcation call test. This function can be accessed only by obj.test where you can imagine obj to be a class.

where as in the below code

function obj()

obj.prototype.test = function() { alert('Hello?'); };
var obj2 = new obj();

The obj has become a class which can now be instantiated. Multiple instances of obj can exist and they all have the test function.

The above is my understanding. I am making it a community wiki, so people can correct me if I am wrong.


The seven Koans of prototype

As Ciro San descended Mount Fire Fox after deep meditation, his mind was clear and peaceful.

His hand however, was restless, and by itself grabbed a brush and jotted down the following notes.

0) Two different things can be called "prototype":

  • the prototype property, as in obj.prototype

  • the prototype internal property, denoted as [[Prototype]] in ES5.

    It can be retrieved via the ES5 Object.getPrototypeOf().

    Firefox makes it accessible through the __proto__ property as an extension. ES6 now mentions some optional requirements for __proto__.

1) Those concepts exist to answer the question:

When I do, where does JS look for .property?

Intuitively, classical inheritance should affect property lookup.


  • __proto__ is used for the dot . property lookup as in
  • .prototype is not used for lookup directly, only indirectly as it determines __proto__ at object creation with new.

Lookup order is:

  • obj properties added with obj.p = ... or Object.defineProperty(obj, ...)
  • properties of obj.__proto__
  • properties of obj.__proto__.__proto__, and so on
  • if some __proto__ is null, return undefined.

This is the so-called prototype chain.

You can avoid . lookup with obj.hasOwnProperty('key') and Object.getOwnPropertyNames(f)

3) There are two main ways to set obj.__proto__:

  • new:

    var F = function() {}
    var f = new F()

    then new has set:

    f.__proto__ === F.prototype

    This is where .prototype gets used.

  • Object.create:

     f = Object.create(proto)


    f.__proto__ === proto

4) The code:

var F = function(i) { this.i = i }
var f = new F(1)

Corresponds to the following diagram (some Number stuff is omitted):

(Function)       (  F  )                                      (f)----->(1)
 |  ^             | | ^                                        |   i    |
 |  |             | | |                                        |        |
 |  |             | | +-------------------------+              |        |
 |  |constructor  | |                           |              |        |
 |  |             | +--------------+            |              |        |
 |  |             |                |            |              |        |
 |  |             |                |            |              |        |
 |[[Prototype]]   |[[Prototype]]   |prototype   |constructor   |[[Prototype]]
 |  |             |                |            |              |        |
 |  |             |                |            |              |        |
 |  |             |                | +----------+              |        |
 |  |             |                | |                         |        |
 |  |             |                | | +-----------------------+        |
 |  |             |                | | |                                |
 v  |             v                v | v                                |
(Function.prototype)              (F.prototype)                         |
 |                                 |                                    |
 |                                 |                                    |
 |[[Prototype]]                    |[[Prototype]]          [[Prototype]]|
 |                                 |                                    |
 |                                 |                                    |
 | +-------------------------------+                                    |
 | |                                                                    |
 v v                                                                    v
(Object.prototype)                                       (Number.prototype)
 | | ^
 | | |
 | | +---------------------------+
 | |                             |
 | +--------------+              |
 |                |              |
 |                |              |
 |[[Prototype]]   |constructor   |prototype
 |                |              |
 |                |              |
 |                | -------------+
 |                | |
 v                v |
(null)           (Object)

This diagram shows many language predefined object nodes:

  • null
  • Object
  • Object.prototype
  • Function
  • Function.prototype
  • 1
  • Number.prototype (can be found with (1).__proto__, parenthesis mandatory to satisfy syntax)

Our 2 lines of code only created the following new objects:

  • f
  • F
  • F.prototype

i is now a property of f because when you do:

var f = new F(1)

it evaluates F with this being the value that new will return, which then gets assigned to f.

5) .constructor normally comes from F.prototype through the . lookup:

f.constructor === F
Object.getPrototypeOf(f) === F.prototype
F.prototype.constructor === f.constructor

When we write f.constructor, JavaScript does the . lookup as:

  • f does not have .constructor
  • f.__proto__ === F.prototype has .constructor === F, so take it

The result f.constructor == F is intuitively correct, since F is used to construct f, e.g. set fields, much like in classic OOP languages.

6) Classical inheritance syntax can be achieved by manipulating prototypes chains.

ES6 adds the class and extends keywords, which are mostly syntax sugar for previously possible prototype manipulation madness.

class C {
    constructor(i) {
        this.i = i
    inc() {
        return this.i + 1

class D extends C {
    constructor(i) {
    inc2() {
        return this.i + 2
// Inheritance syntax works as expected.
c = new C(1) === 2
(new D(1)).inc() === 2
(new D(1)).inc2() === 3
// "Classes" are just function objects.
C.constructor === Function
C.__proto__ === Function.prototype
D.constructor === Function
// D is a function "indirectly" through the chain.
D.__proto__ === C
D.__proto__.__proto__ === Function.prototype
// "extends" sets up the prototype chain so that base class
// lookups will work as expected
var d = new D(1)
d.__proto__ === D.prototype
D.prototype.__proto__ === C.prototype
// This is what `` actually does. ===
// Class variables
// No ES6 syntax sugar apparently:
C.c = 1
C.c === 1
// Because `D.__proto__ === C`.
D.c === 1
// Nothing makes this work.
d.c === undefined

Simplified diagram without all predefined objects:

 |   i
 v    __proto__
(C)<--------------(D)         (d)
| |                |           |
| |                |           |
| |prototype       |prototype  |[[Prototype]] 
| |                |           |
| |                |           |
| |                | +---------+
| |                | |
| |                | |
| |                v v
|[[Prototype]]    (D.prototype)--------> (inc2 function object)
| |                |             inc2
| |                |
| |                |[[Prototype]]
| |                |
| |                |
| | +--------------+
| | |
| | |
| v v
| (C.prototype)------->(inc function object)
|                inc

Let's take a moment to study how the following works:

c = new C(1) === 2

The first line sets c.i to 1 as explained in "4)".

On the second line, when we do:
  • .inc is found through the [[Prototype]] chain: c -> C -> C.prototype -> inc
  • when we call a function in Javascript as X.Y(), JavaScript automatically sets this to equal X inside the Y() function call!

The exact same logic also explains and d.inc2.

This article mentions further effects of class worth knowing. Some of them may not be achievable without the class keyword (TODO check which):


After reading this thread, I feel confused with JavaScript Prototype Chain, then I found these charts *[[protytype]]* and <code>prototype</code> property of function objects

it's a clear chart to show JavaScript Inheritance by Prototype Chain


this one contains a example with code and several nice diagrams.

prototype chain ultimately falls back to Object.prototype.

prototype chain can be technically extended as long as you want, each time by setting the prototype of the subclass equal to an object of the parent class.

Hope it's also helpful for you to understand JavaScript Prototype Chain.


Every object has an internal property, [[Prototype]], linking it to another object:

object [[Prototype]] -> anotherObject

In traditional javascript, the linked object is the prototype property of a function:

object [[Prototype]] -> aFunction.prototype

Some environments expose [[Prototype]] as __proto__:

anObject.__proto__ === anotherObject

You create the [[Prototype]] link when creating an object.

// (1) Object.create:
var object = Object.create(anotherObject)
// object.__proto__ = anotherObject

// (2) ES6 object initializer:
var object = { __proto__: anotherObject };
// object.__proto__ = anotherObject

// (3) Traditional JavaScript:
var object = new aFunction;
// object.__proto__ = aFunction.prototype

So these statements are equivalent:

var object = Object.create(Object.prototype);
var object = { __proto__: Object.prototype }; // ES6 only
var object = new Object;

A new statement doesn't show the link target (Object.prototype) itself; instead the target is implied by the constructor (Object).


  • Every object has a link, [[Prototype]], sometimes exposed as __proto__.
  • Every function has a prototype property.
  • Objects created with new are linked to the prototype property of their constructor.
  • If a function is never used as a constructor, its prototype property will go unused.
  • If you don't need a constructor, use Object.create instead of new.

Javascript doesn't have inheritance in the usual sense, but it has the prototype chain.

prototype chain

If a member of an object can't be found in the object it looks for it in the prototype chain. The chain consists of other objects. The prototype of a given instance can be accessed with the __proto__ variable. Every object has one, as there is no difference between classes and instances in javascript.

The advantage of adding a function / variable to the prototype is that it has to be in the memory only once, not for every instance.

It's also useful for inheritance, because the prototype chain can consist of many other objects.


This article is long. But I am sure it will clear most of your queries regarding the "prototypical" nature of JavaScript Inheritance. And even more. Please read the complete article.

JavaScript basically has two kinds of data types

  • Non objects
  • Objects

Non objects

Following are the Non object data types

  • string
  • number (including NaN and Infinity)
  • boolean values(true,false)
  • undefined

These data types return following when you use the typeof operator

typeof "string literal" (or a variable containing string literal) === 'string'

typeof 5 (or any numeric literal or a variable containing numeric literal or NaN or Infynity) === 'number'

typeof true (or false or a variable containing true or false) === 'boolean'

typeof undefined (or an undefined variable or a variable containing undefined) === 'undefined'

The string,number and boolean data types can be represented both as Objects and Non objects.When they are represented as objects their typeof is always === 'object'. We shall come back to this once we understand the object data types.


The object datatypes can be further divided into two types

  1. Function type objects
  2. Non Function type objects

The Function type objects are the ones that return the string 'function' with typeof operator. All the user defined functions and all the JavaScript built in objects that can create new objects by using new operator fall into this category. For eg.

  • Object
  • String
  • Number
  • Boolean
  • Array
  • Typed Arrays
  • RegExp
  • Function
  • All the other built in objects that can create new objects by using new operator
  • function UserDefinedFunction(){ /*user defined code */ }

So, typeof(Object) === typeof(String) === typeof(Number) === typeof(Boolean) === typeof(Array) === typeof(RegExp) === typeof(Function) === typeof(UserDefinedFunction) === 'function'

All the Function type objects are actually instances of the built in JavaScript object Function (including the Function object i.e it is recursively defined). It is as if the these objects have been defined in the following way

var Object= new Function ([native code for object Object])
var String= new Function ([native code for object String])
var Number= new Function ([native code for object Number])
var Boolean= new Function ([native code for object Boolean])
var Array= new Function ([native code for object Array])
var RegExp= new Function ([native code for object RegExp])
var Function= new Function ([native code  for object Function])
var UserDefinedFunction= new Function ("user defined code")

As mentioned, the Function type objects can further create new objects using the new operator. For e.g an object of type Object, String, Number, Boolean, Array, RegExp Or UserDefinedFunction can be created by using

var a=new Object() or var a=Object() or var a={} //Create object of type Object
var a=new String() //Create object of type String
var a=new Number() //Create object of type Number
var a=new Boolean() //Create object of type Boolean
var a=new Array() or var a=Array() or var a=[]  //Create object of type Array
var a=new RegExp() or var a=RegExp() //Create object of type RegExp
var a=new UserDefinedFunction() 

The objects thus created are all Non Function type objects and return their typeof==='object'. In all these cases the object "a" cannot further create objects using operator new. So the following is wrong

var b=new a() //error. a is not typeof==='function'

The built in object Math is typeof==='object'. Hence a new object of type Math cannot be created by new operator.

var b=new Math() //error. Math is not typeof==='function'

Also notice that Object,Array and RegExp functions can create a new object without even using operator new. However the follwing ones don't.

var a=String() // Create a new Non Object string. returns a typeof==='string' 
var a=Number() // Create a new Non Object Number. returns a typeof==='number'
var a=Boolean() //Create a new Non Object Boolean. returns a typeof==='boolean'

The user defined functions are special case.

var a=UserDefinedFunction() //may or may not create an object of type UserDefinedFunction() based on how it is defined.

Since the Function type objects can create new objects they are also called Constructors.

Every Constructor/Function (whether built in or user defined) when defined automatically has a property called "prototype" whose value by default is set as an object. This object itself has a property called "constructor" which by default references back the Constructor/Function .

For example when we define a function

function UserDefinedFunction()

following automatically happens


This "prototype" property is only present in the Function type objects (and never in Non Function type objects).

This is because when a new object is created (using new operator)it inherits all properties and methods from Constructor function's current prototype object i.e. an internal reference is created in the newly created object that references the object referenced by Constructor function's current prototype object.

This "internal reference" that is created in the object for referencing inherited properties is known as the object's prototype (which references the object referenced by Constructor's "prototype" property but is different from it). For any object (Function or Non Function) this can be retrieved using Object.getPrototypeOf() method. Using this method one can trace the prototype chain of an object.

Also, every object that is created (Function type or Non Function type) has a "constructor" property which is inherited from the object referenced by prototype property of the Constructor function. By default this "constructor" property references the Constructor function that created it (if the Constructor Function's default "prototype" is not changed).

For all Function type objects the constructor function is always function Function(){}

For Non Function type objects (e.g Javascript Built in Math object) the constructor function is the function that created it. For Math object it is function Object(){}.

All the concept explained above can be a little daunting to understand without any supporting code. Please go through the following code line by line to understand the concept. Try to execute it to have a better understanding.

function UserDefinedFunction()


/* creating the above function automatically does the following as mentioned earlier



var newObj_1=new UserDefinedFunction()

alert(Object.getPrototypeOf(newObj_1)===UserDefinedFunction.prototype)  //Displays true

alert(newObj_1.constructor) //Displays function UserDefinedFunction

//Create a new property in UserDefinedFunction.prototype object


alert(newObj_1.TestProperty) //Displays "test"

alert(Object.getPrototypeOf(newObj_1).TestProperty)// Displays "test"

//Create a new Object

var objA = {
        property1 : "Property1",


//assign a new object to UserDefinedFunction.prototype

alert(Object.getPrototypeOf(newObj_1)===UserDefinedFunction.prototype)  //Displays false. The object referenced by UserDefinedFunction.prototype has changed

//The internal reference does not change
alert(newObj_1.constructor) // This shall still Display function UserDefinedFunction

alert(newObj_1.TestProperty) //This shall still Display "test" 

alert(Object.getPrototypeOf(newObj_1).TestProperty) //This shall still Display "test"

//Create another object of type UserDefinedFunction
var newObj_2= new UserDefinedFunction();

alert(Object.getPrototypeOf(newObj_2)===objA) //Displays true.

alert(newObj_2.constructor) //Displays function Array()

alert(newObj_2.property1) //Displays "Property1"

alert(Object.getPrototypeOf(newObj_2).property1) //Displays "Property1"

//Create a new property in objA

alert(objA.property2) //Displays "Property2"

alert(UserDefinedFunction.prototype.property2) //Displays "Property2"

alert(newObj_2.property2) // Displays Property2

alert(Object.getPrototypeOf(newObj_2).property2) //Displays  "Property2"

The prototype chain of every object ultimately traces back to Object.prototype (which itself does not have any prototype object) . Following code can be used for tracing the prototype chain of an object

var o=Starting object;

do {
    alert(o + "\n" + Object.getOwnPropertyNames(o))


The prototype chain for various objects work out as follows.

  • Every Function object (including built in Function object)-> Function.prototype -> Object.prototype -> null
  • Simple Objects (created By new Object() or {} including built in Math object)-> Object.prototype -> null
  • Object created with new or Object.create -> One or More prototype chains -> Object.prototype -> null

For creating an object without any prototype use the following:

var o=Object.create(null)
alert(Object.getPrototypeOf(o)) //Displays null

One might think that setting the prototype property of the Constructor to null shall create an object with a null prototype. However in such cases the newly created object's prototype is set to Object.prototype and its constructor is set to function Object. This is demonstrated by the following code

function UserDefinedFunction(){}
UserDefinedFunction.prototype=null// Can be set to any non object value (number,string,undefined etc.)

var o=new UserDefinedFunction()
alert(Object.getPrototypeOf(o)==Object.prototype)   //Displays true
alert(o.constructor)    //Displays Function Object

Following in the summary of this article

  • There are two types of objects Function types and Non Function types
  • Only Function type objects can create a new object using the operator new. The objects thus created are Non Function type objects. The Non Function type objects cannot further create an object using operator new.

  • All Function type objects by default have a "prototype" property. This "prototype" property references an object that has a "constructor" property that by default references the Function type object itself.

  • All objects (Function type and Non Function type) have a "constructor" property that by default references the Function type object/Constructor that created it.

  • Every object that gets created internally references the object referenced by "prototype" property of the Constructor that created it. This object is known as the created object's prototype (which is different from Function type objects "prototype" property which it references) . This way the created object can directly access the methods and properties defined in object referenced by the Constructor's "prototype" property (at the time of object creation).

  • An object's prototype (and hence its inherited property names) can be retrieved using the Object.getPrototypeOf() method. In fact this method can be used for navigating the entire prototype chain of the object.

  • The prototype chain of every object ultimately traces back to Object.prototype (Unless the object is created using Object.create(null) in which case the object has no prototype).

  • typeof(new Array())==='object' is by design of language and not a mistake as pointed by Douglas Crockford

  • Setting the prototype property of the Constructor to null(or undefined,number,true,false,string) shall not create an object with a null prototype. In such cases the newly created object's prototype is set to Object.prototype and its constructor is set to function Object.

Hope this helps.


The concept of prototypal inheritance is one of the most complicated for many developers. Let's try to understand the root of problem to understand prototypal inheritance better. Let's start with a plain function.

enter image description here

If we use a new operator on the Tree function, we call it as a constructor function.

enter image description here

Every JavaScript function has a prototype. When you log the Tree.prototype, you get...

enter image description here

If you look at the above console.log() output, you could a see a constructor property on Tree.prototype and a __proto__ property too. The __proto__ represents the prototype that this function is based off, and since this is just a plain JavaScript function with no inheritance set up yet, it refers to the Object prototype which is something just built in to JavaScript...

This has things like .toString, .toValue, .hasOwnProperty etc...

__proto__ which was brought my mozilla is deprecated and is replaced by Object.getPrototypeOf method to get the object's prototype.

enter image description here

Object.getPrototypeOf(Tree.prototype); // Object {} 

Let's add a method to our Tree prototype.

enter image description here

We have modified the Root and added a function branch to it.

enter image description here

That means when you create an instance of Tree, you can call it's branch method.

enter image description here

We can also add primitives or objects to our Prototype.

enter image description here

Let's add a child-tree to our Tree.

enter image description here

Here the Child inherits its prototype from Tree, what we are doing here is using Object.create() method to create a new object based off what you pass, here it is Tree.prototype. In this case what we're doing is setting the prototype of Child to a new object that looks identical to the Tree prototype. Next we are setting the Child's constructor to Child, if we don't it would point to Tree().

enter image description here

Child now has its own prototype, its __proto__ points to Tree and Tree's prototype points to base Object.

   - branch
      -etc., etc.

Now you create an instance of Child and call branch which is originally available in Tree. We haven't actually defined our branch on the Child prototype. BUT, in the Root prototype which Child inherits from.

enter image description here

In JS everything is not an object, everything can act like an object.

Javascript has primitives like strings, number, booleans, undefined, null. They are not object(i.e reference types), but certainly can act like an object. Let's look at an example here.

enter image description here

In the first line of this listing, a primitive string value is assigned to name. The second line treats name like an object and calls charAt(0) using dot notation.

This is what happens behind the scenes: // what the JavaScript engine does

enter image description here

The String object exists only for one statement before it’s destroyed (a process called autoboxing). Let's again get back to our prototypal inheritance.

  • Javascript supports inheritance via delegation based on prototypes.
  • Each Function has a prototype property, which refers to another object.
  • properties/functions are looked from the object itself or via prototype chain if it does not exist

A prototype in JS is an object which yields you to the parent of another object. [ie.. delegation] Delegation means that if you are unable to do something, you’ll tell someone else to do it for you.

enter image description here

If you look up the above fiddle, dog has access to toString method, but its not available in it, but available via the prototype chain which delegates to Object.prototype

enter image description here

If you look at the below one, we are trying to access the call method which is available in every function.

enter image description here

If you look up the above fiddle, Profile Function has access to call method, but its not available in it, but available via the prototype chain which delegates to Function.prototype

enter image description here

Note: prototype is a property of the function constructor, whereas __proto__ is a property of the objects constructed from the function constructor. Every function comes with a prototype property whose value is an empty object. When we create an instance of the function, we get an internal property [[Prototype]] or __proto__ whose reference is the prototype of the Function constructor.

enter image description here

The above diagram looks bit complicated, but brings out the whole picture on how prototype chaining works. Let's walk through this slowly:

There are two instance b1 and b2, whose constructor is Bar and parent is Foo and has two methods from prototype chain identify and speak via Bar and Foo

enter image description here

If you look up the code above, we have Foo constructor who has the method identify() and Bar constructor which has speak method. We create two Bar instance b1 and b2 whose parent type is Foo. Now while calling speak method of Bar, we are able to identify the who is calling the speak via prototype chain.

enter image description here

Bar now has all the methods of Foo which are defined in its prototype. Let's dig further in understanding the Object.prototype and Function.prototype and how they are related. If you look up the constructor of Foo, Bar and Object are Function constructor.

enter image description here

The prototype of Bar is Foo, prototype of Foo is Object and if you look closely the prototype of Foo is related to Object.prototype.

enter image description here

Before we close this down, let's just wrap with a small piece of code here to summarize everything above. We are using instanceof operator here to check whether an object has in its prototype chain the prototype property of a constructor which below summarizes the entire big diagram.

enter image description here

I hope this add's some information, I know this kinda could be big to grasp... in simple words its it's just objects linked to objects!!!!


what is the exact purpose of this ".prototype" property?

The interface to standard classes become extensible. For example, you are using the Array class and you also need to add a custom serializer for all your array objects. Would you spend time coding up a subclass, or use composition or ... The prototype property solves this by letting the users control the exact set of members/methods available to a class.

Think of prototypes as an extra vtable-pointer. When some members are missing from the original class, the prototype is looked up at runtime.


It may help to categorise prototype chains into two categories.

Consider the constructor:

 function Person() {}

The value of Object.getPrototypeOf(Person) is a function. In fact, it is Function.prototype. Since Person was created as a function, it shares the same prototype function object that all functions have. It is the same as Person.__proto__, but that property should not be used. Anyway, with Object.getPrototypeOf(Person) you effectively walk up the ladder of what is called the prototype chain.

The chain in upward direction looks like this:

    Person ? Function.prototype ? Object.prototype (end point)

Important is that this prototype chain has little to do with the objects that Person can construct. Those constructed objects have their own prototype chain, and this chain can potentially have no close ancestor in common with the one mentioned above.

Take for example this object:

var p = new Person();

p has no direct prototype-chain relationship with Person. Their relationship is a different one. The object p has its own prototype chain. Using Object.getPrototypeOf, you'll find the chain is as follows:

    p ? Person.prototype ? Object.prototype (end point)

There is no function object in this chain (although that could be).

So Person seems related to two kinds of chains, which live their own lives. To "jump" from one chain to the other, you use:

  1. .prototype: jump from the constructor's chain to the created-object's chain. This property is thus only defined for function objects (as new can only be used on functions).

  2. .constructor: jump from the created-object's chain to the constructor's chain.

Here is a visual presentation of the two prototype chains involved, represented as columns:

enter image description here

To summarise:

The prototype property gives no information of the subject's prototype chain, but of objects created by the subject.

It is no surprise that the name of the property prototype can lead to confusion. It would maybe have been clearer if this property had been named prototypeOfConstructedInstances or something along that line.

You can jump back and forth between the two prototype chains:

Person.prototype.constructor === Person

This symmetry can be broken by explicitly assigning a different object to the prototype property (more about that later).

Create one Function, Get Two Objects

Person.prototype is an object that was created at the same time the function Person was created. It has Person as constructor, even though that constructor did not actually execute yet. So two objects are created at the same time:

  1. The function Person itself
  2. The object that will act as prototype when the function is called as a constructor

Both are objects, but they have different roles: the function object constructs, while the other object represents the prototype of any object that function will construct. The prototype object will become the parent of the constructed object in its prototype chain.

Since a function is also an object, it also has its own parent in its own prototype chain, but recall that these two chains are about different things.

Here are some equalities that could help grasp the issue -- all of these print true:

function Person() {};

// This is prototype chain info for the constructor (the function object):
console.log(Object.getPrototypeOf(Person) === Function.prototype);
// Step further up in the same hierarchy:
console.log(Object.getPrototypeOf(Function.prototype) === Object.prototype);
console.log(Object.getPrototypeOf(Object.prototype) === null);
console.log(Person.__proto__ === Function.prototype);
// Here we swap lanes, and look at the constructor of the constructor
console.log(Person.constructor === Function);
console.log(Person instanceof Function);

// Person.prototype was created by Person (at the time of its creation)
// Here we swap lanes back and forth:
console.log(Person.prototype.constructor === Person);
// Although it is not an instance of it:
console.log(!(Person.prototype instanceof Person));
// Instances are objects created by the constructor:
var p = new Person();
// Similarly to what was shown for the constructor, here we have
// the same for the object created by the constructor:
console.log(Object.getPrototypeOf(p) === Person.prototype);
console.log(p.__proto__ === Person.prototype);
// Here we swap lanes, and look at the constructor
console.log(p.constructor === Person);
console.log(p instanceof Person);

Adding levels to the prototype chain

Although a prototype object is created when you create a constructor function, you can ignore that object, and assign another object that should be used as prototype for any subsequent instances created by that constructor.

For instance:

function Thief() { }
var p = new Person();
Thief.prototype = p; // this determines the prototype for any new Thief objects:
var t = new Thief();

Now the prototype chain of t is one step longer than that of p:

    t ? p ? Person.prototype ? Object.prototype (end point)

The other prototype chain is not longer: Thief and Person are siblings sharing the same parent in their prototype chain:

    Thief  } ? Function.prototype ? Object.prototype (end point)

The earlier presented graphic can then be extended to this (the original Thief.prototype is left out):

enter image description here

The blue lines represent prototype chains, the other coloured lines represent other relationships:

  • between an object and its constructor
  • between a constructor and the prototype object that will be used for constructing objects

The Definitive Guide to Object-Oriented JavaScript - a very concise and clear ~30min video explanation of the asked question (Prototypal Inheritance topic begins from 5:45, although I'd rather listen to the whole video). The author of this video also made JavaScript object visualizer website image description here enter image description here


I found it helpful to explain the "prototype chain" as recursive convention when obj_n.prop_X is being referenced:

if obj_n.prop_X doesn't exist, check obj_n+1.prop_X where obj_n+1 = obj_n.[[prototype]]

If the prop_X is finally found in the k-th prototype object then

obj_1.prop_X = obj_1.[[prototype]].[[prototype]]..(k-times)..[[prototype]].prop_X

You can find a graph of the relation of Javascript objects by their properties here:

js objects graph


When a constructor creates an object, that object implicitly references the constructor’s “prototype” property for the purpose of resolving property references. The constructor’s “prototype” property can be referenced by the program expression constructor.prototype, and properties added to an object’s prototype are shared, through inheritance, by all objects sharing the prototype.


Let me tell you my understanding of prototypes. I am not going to compare the inheritance here with other languages. I wish people would stop comparing languages, and just understand the language as itself. Understanding prototypes and prototypal inheritance is so simple, as I will show you below.

Prototype is like a model, based on which you create a product. The crucial point to understand is that when you create an object using another object as it's prototype, the link between the prototype and the product is ever-lasting. For instance:

var model = {x:2};
var product = Object.create(model);
model.y = 5;

Every object contains an internal property called the [[prototype]], which can be accessed by the Object.getPrototypeOf() function. Object.create(model) creates a new object and sets it's [[prototype]] property to the object model. Hence when you do Object.getPrototypeOf(product), you will get the object model.

Properties in the product are handled in the following way:

  • When a property is accessed to just read it's value, its looked up in the scope chain. The search for the variable starts from the product upwards to it's prototype. If such a variable is found in the search, the search is stopped right there, and the value is returned. If such a variable cannot be found in the scope chain, undefined is returned.
  • When a property is written(altered), then the property is always written on the product object. If the product does not have such a property already, it is implicitly created and written.

Such a linking of objects using the prototype property is called prototypal inheritance. There, it is so simple, agree?


There's two distinct but related entities here that need explaining:

  • The .prototype property of functions.
  • The [[Prototype]][1] property of all objects[2].

These are two different things.

The [[Prototype]] property:

This is a property that exists on all[2] objects.

What's stored here is another object, which, as an object itself, has a [[Prototype]] of its own that points to another object. That other object has a [[Prototype]] of its own. This story continues until you reach the prototypical object that provides methods that are accessible on all objects (like .toString).

The [[Prototype]] property is part of what forms the [[Prototype]] chain. This chain of [[Prototype]] objects is what is examined when, for example, [[Get]] or [[Set]] operations are performed on an object:

var obj = {}
obj.a         // [[Get]] consults prototype chain
obj.b = 20    // [[Set]] consults prototype chain

The .prototype property:

This is a property that is only found on functions. Using a very simple function:

function Bar(){};

The .prototype property holds an object that will be assigned to b.[[Prototype]] when you do var b = new Bar. You can easily examine this:

// Both assign Bar.prototype to b1/b2[[Prototype]]
var b = new Bar;
// Object.getPrototypeOf grabs the objects [[Prototype]]
console.log(Object.getPrototypeOf(b) === Bar.prototype) // true

One of the most important .prototypes is that of the Object function. This prototype holds the prototypical object that all [[Prototype]] chains contain. On it, all the available methods for new objects are defined:

// Get properties that are defined on this object

Now, since .prototype is an object, it has a [[Prototype]] property. When you don't make any assignments to Function.prototype, the .prototype's [[Prototype]] points to the prototypical object (Object.prototype). This is automatically performed anytime you create a new function.

This way, any time you do new Bar; the prototype chain is set up for you, you get everything defined on Bar.prototype and everything defined on Object.prototype:

var b = new Bar;
// Get all Bar.prototype properties
console.log(b.__proto__ === Bar.prototype)
// Get all Object.prototype properties
console.log(b.__proto__.__proto__ === Object.prototype)

When you do make assignments to Function.prototype all you are doing is extending the prototype chain to include another object. It's like an insertion in a singly linked list.

This basically alters the [[Prototype]] chain allowing properties that are defined on the object assigned to Function.prototype to be seen by any object created by the function.

[1: That won't confuse anyone; made available via the __proto__ property in many implementations.
[2]: All except null.


Another attempt to explain JavaScript prototype-based inheritance with better pictures

Simple objects inheritanse


Consider the following keyValueStore object :

var keyValueStore = (function() {
    var count = 0;
    var kvs = function() {
        count++; = {};
        this.get = function(key) { return[key]; };
        this.set = function(key, value) {[key] = value; };
        this.delete = function(key) { delete[key]; };
        this.getLength = function() {
            var l = 0;
            for (p in l++;
            return l;

    return  { // Singleton public properties
        'create' : function() { return new kvs(); },
        'count' : function() { return count; }

I can create a new instance of this object by doing this :

kvs = keyValueStore.create();

Each instance of this object would have the following public properties :

  • data
  • get
  • set
  • delete
  • getLength

Now, suppose we create 100 instances of this keyValueStore object. Even though get, set, delete, getLength will do the exact same thing for each of these 100 instances, every instance has its own copy of this function.

Now, imagine if you could have just a single get, set, delete and getLength copy, and each instance would reference that same function. This would be better for performance and require less memory.

That's where prototypes come in. A prototype is a "blueprint" of properties that is inherited but not copied by instances. So this means that it exists only once in memory for all instances of an object and is shared by all of those instances.

Now, consider the keyValueStore object again. I could rewrite it like this :

var keyValueStore = (function() {
    var count = 0;
    var kvs = function() {
        count++; = {};

    kvs.prototype = {
        'get' : function(key) { return[key]; },
        'set' : function(key, value) {[key] = value; },
        'delete' : function(key) { delete[key]; },
        'getLength' : function() {
            var l = 0;
            for (p in l++;
            return l;

    return  {
        'create' : function() { return new kvs(); },
        'count' : function() { return count; }

This does EXACTLY the same as the previous version of the keyValueStore object, except that all of its methods are now put in a prototype. What this means, is that all of the 100 instances now share these four methods instead of each having their own copy.



  • Functions are objects in javascript and thus can have properties
  • (Constructor) functions always have a prototype property
  • When a function is used as a constructor with the new keyword the object gets prototype. A reference to this prototype can be found on the __proto__ property of the newly created object.
  • This __proto__ property refers to the prototype property of the constructor function.


function Person (name) { = name;

let me = new Person('willem');

console.log(Person.prototype) // Person has a prototype property

console.log(Person.prototype === me.__proto__) // the __proto__ property of the instance refers to prototype property of the function.

Why is this usefull:

Javascript has a mechanism when looking up properties on Objects which is called 'prototypal inheritance', here is what is basically does:

  • First is checked if the property is located on the Object itself. If so this property is returned.
  • If the property is not located on the object itself it will 'climb up the protochain'. It basically looks at the object referred to by the proto property. There it checks if the property is available on the object referred to by proto
  • If the property isn't located on the proto object it will climb up the proto chain all the way up to Object object.
  • If it cannot find the property nowhere on the object and its prototype chain it will return undefined.

For example:

function Person(name) { = name;

let mySelf = new Person('Willem');

console.log(mySelf.__proto__ === Person.prototype);

console.log(mySelf.__proto__.__proto__ === Object.prototype);


The __proto__ property has been deprecated, although it is implemented in most modern browsers a better way to obtain the prototype object reference would be:



I always like analogies when it comes to understand this type of stuff. 'Prototypical inheritance' is pretty confusing in comparison to class bass inheritance in my opinion, even though prototypes are much simpler paradigm. In fact with prototypes, there really is no inheritance, so the name in and of itself misleading, it's more a type of 'delegation'.

Imagine this ....

You're in high-school, and you're in class and have a quiz that's due today, but you don't have a pen to fill out your answers. Doh!

You're sitting next to your friend Finnius, who might have a pen. You ask, and he looks around his desk unsuccessfully, but instead of saying "I don't have a pen", he's a nice friend he checks with his other friend Derp if he has a pen. Derp does indeed have a spare pen and passes it back to Finnius, who passes it over to you to complete your quiz. Derp has entrusted the pen to Finnius, who has delegated the pen to you for use.

What is important here is that Derp does not give the pen to you, as you don't have a direct relationship with him.

This, is a simplified example of how prototypes work, where a tree of data is searched for the thing you're looking for.


another scheme showing __proto__, prototype and constructor relations: enter image description here


It's just that you already have an object with but you still don't have an object when using the constructor syntax.


The Prototype creates new object by cloning existing object. So really when we think about prototype we can really think cloning or making a copy of something instead of making it up.


It's important to understand that there is a distinction between an object's prototype (which is available via Object.getPrototypeOf(obj), or via the deprecated __proto__ property) and the prototype property on constructor functions. The former is the property on each instance, and the latter is the property on the constructor. That is, Object.getPrototypeOf(new Foobar()) refers to the same object as Foobar.prototype.



Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.