Console Learner — An interactive JavaScript course.


4.5 Prototypes

The image below shows the prototype chain for the code in this example:

Object prototype chain

>>>
function Test(val) { this.a = val; }


  
>>>
Test.prototype.b = 42;

  
The function prototype property contains an empty object that is used when instances are created with new.
>>>
var one = new Test(1), two = new Test(2);

  
The function prototype object is linked to the instances upon creation. The prototype chain shouldn't be modified after object creation, but it is possible using Object.setPrototypeOf() (since ES6 in 2015).
>>>
one
{ "a": 1, "b": 42 }
The properties in the prototype are visible for all instances.
>>>
two.b = 7337;


  
>>>
two
{ "a": 2, "b": 7337 }
Changes are stored in the object instance, regardless of the property origin in the prototype chain.
>>>
one
{ "a": 1, "b": 42 }
This means that other instances retain the value from the prototype.
>>>
Test.prototype.c = 'test';


  
>>>
one
{ "a": 1, "b": 42, "c": "test" }
Changes can also be made directly to the prototype. These will be visible in all instances, even those created previously.
>>>
Object.getPrototypeOf(one)
{ "b": 42, "c": "test" }
Using the built-in Object.getPrototypeOf() function we can inspect an object prototype.
>>>
one.hasOwnProperty('b')
false
The built-in hasOwnProperty() method (or Object.hasOwn() since ES13 in 2022) can be used to check if a property is set in the object instance.
>>>

The console allows you to interact with the course material and examples. Use the following keys:

A special logging function is also available:


Need more magic? Check out the other developer tools on this site.