javascript interactive

JavaScript Interactive — a console crash course


4.5 Prototypes

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.
  • Object Prototypes. All JavaScript objects inherit a prototype object. Property lookup is performed first in the object instance, and thereafter in the object prototype.
  • Default Prototype. The default prototype is the built-in Object.prototype. But any object can be used as a prototype.
  • Prototype Chains. The prototype objects will also inherit a prototype. This forms a chain of prototype objects back to Object.prototype.
>>>
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 cannot be modified after object creation.
>>>
one
{ "a": 1, "b": 42 }
The properties in the prototype are available in all instances.
>>>
two.b = 7337;

  
>>>
two
{ "a": 2, "b": 7337 }
Property changes are made to the object instance, regardless of where the property previously lived in the prototype chain.
>>>
one
{ "a": 1, "b": 42 }
This means that other instances retain the property 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 immediately visible in all instances, even those created previously.
>>>
Object.getPrototypeOf(one)
{ "b": 42, "c": "test" }
Using the built-in Object.getPrototypeOf() function (or the constructor and prototype properties) we can inspect an object prototype.
>>>
one.hasOwnProperty('b')
false
The built-in hasOwnProperty() method can also be used to check if a property belongs to the object instance.
>>>
print(one, true);

  
In this console, the easiest way to inspect a prototype chain is to use the print(..., true) function.
>>>

Index 1 2 3 4 5 6 7 8