What is a Prototype in JavaScript?
JavaScript uses objects as its basic building blocks. Like cells in our body, JavaScript objects have a nucleus that contains the code that gives cells their capabilities. This is the object’s prototype.
Every object has a prototype. To see the prototype of the default JavaScript Object, open a Console window and enter:
Object.prototype;
What you’ll get back are the methods available to be called on every JavaScript object. These may include:
{
constructor: ƒ Object(),
hasOwnProperty: ƒ hasOwnProperty(),
isPrototypeOf: ƒ isPrototypeOf(),
propertyIsEnumerable: ƒ propertyIsEnumerable(),
toLocaleString: ƒ toLocaleString(),
toString: ƒ toString(),
valueOf: ƒ valueOf(),
__defineGetter__: ƒ __defineGetter__(),
__defineSetter__: ƒ __defineSetter__(),
__lookupGetter__: ƒ __lookupGetter__(),
__lookupSetter__: ƒ __lookupSetter__(),
__proto__: null,
get __proto__: ƒ __proto__(),
set __proto__: ƒ __proto__()
}
Calling .prototype on a standard JavaScript type in the browser Console, provides a quick way to reference the available properties and methods of the type. If your Console allows you to inspect the contents of the constructor function in Object, you’ll find it contains 25 or more additional methods.
Prototype Inheritance
The Object.prototype is itself an object that contains a prototype of null. This is the earliest ancestor in the prototype lineage, and it is accessible with the following:
Object.getPrototypeOf(Object.prototype);
Using the Console in your web browser you can alternately use the non-standard .__proto__ accessor to access the null prototype:
Object.prototype.__proto__;
The default Object type is the basic building block from which all other JavaScript types are created. Therefore, standard type objects like Array , String , and Number have access to Object ’s prototype. Let’s study the ancestral prototype chain of the Array object.
To see the Array prototype, open the Console and type:
Array.prototype;
To access the default Object prototype from within the Array type prototype, use:
Object.getPrototypeOf(Array.prototype);
... or in your browser’s Console you can try:
Array.prototype.__proto__;
To get to the null prototype, one must drill three levels deep:
Object.getPrototypeOf(Object.getPrototypeOf(Array.prototype));
... or more legibly from your browser’s Console, you can try:
Array.prototype.__proto__.__proto__;
Custom objects don’t normally come with a prototype function, but they still have access to the default Object prototype via Object.getPrototypeOf(obj) or in most browsers obj.__proto__. Functions, however, will come with a .prototype method.
While it is possible to modify native prototypes, this practice is not recommended.
Related posts:
Helpful references:
Have feedback on this topic?