Understanding the JavaScript Object's Prototype cover image

Understanding the JavaScript Object’s Prototype

Almost everything in Javascript is an object & while working with Javascript, somehow, you must have encountered (or maybe just seen) the __proto__ in some Javascript variable.

If not, I will show you one.

Here, we are creating a variable named str that will hold a string value “Hello World”.

javascript variable created named str

When we try to access str, we get “Hello World” as result.

accessing the value of variable str

But, if we dive in further, we see that chrome auto-completes the property & shows a suggestion named __proto__ which when accessed, yields the following result:

str variable's prototype intellisense

javascript object's prototype

So, what actually __proto__ is?

This is a shorthand notation for the word prototype which can be considered as an additional storage for an object, that contains the object’s metadata like some properties & methods.

In the image above, we get the methods that we get a list of string extension methods that we can use with the value “Hello World”.
Say, we want to use the charAt method, that we see in the __proto__ list.

We can use it like:

using object prototype's charAt method

We can use any of the object’s prototype method for the object we are working with.

Creating Custom Prototype Method

We already have a huge list of prototype methods, but what if we want to create our custom method?

Now we will see how can we create an object’s prototype method or property.

creating custom prototype method in JavaScript

As we can see in the image, str.__proto__ gives the object name as “String”. We will use this keyword to create our custom prototype method.

To create a custom prototype method, we need to write:

ObjectName.prototype.FunctionName = function() { //this can have parameters as a normal function
	//function code

As in the image below, we have created a prototype method of name myCustomFunction that takes no parameter & has a void return type.

prototype method signature

Hitting enter registered our custom function in the String object’s prototype.

Now, we can call the function we just created in the following way:


See in the image below, how we get our method name as a suggestion in the suggestion list.
Executing the above line of code yields the following output:

calling custom method created in object's prototype

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.