Always remember this.
.protoype can only be used on functions. Period.
Let’s say we have a constructor function called as myInfo
function Info(name,age) {
this.name = name;
this.age = age;
}
We are making a new object with our constructor function called geo.
let geo = new Info('Geo',26);
Now if we console log this we will get our object geo
And you can see that we can access the name and age property.
We can look at the prototype of our object geo using proto
Now try typing geo.prototype
in your console
You won’t find an option called prototype.
Now I just want to re-iterate the fact that we can only use prototype on a function.
Since we are using a constructor function let’s use it on that.
If we type Info.prototype
we will get the following
This is exactly same to geo.__proto__
Carzy isn’t it ?
We can even check if they are the same
But what if, what if we want to add a function to our geo object (technically a method) ?
We can easily do that with
geo.__proto__.hi = function() {console.log('hi')};
The problem comes when we have many such objects
Say we have
let john = new Info('John',20);
let sheila = new Info('Sheila',24);
let gary = new Info('Gary',27);
let kate = new Info('Kate',25);
We we would have to attach the hi function to each and every of our new objects we have created above.
Instead why not just use the prototype of the constructor function.
Just a side note… When we think of .prototype we might have this tendency to think that it shows the prototype, yes it does but logically speaking it is actually like function.customPrototypeIAmMaking
So lets make a sayHello function for Info
Info.prototype.sayHello = function () {console.log(`Hello I am ${this.name}`)};
No matter which object you create with the constructor function Info, you’ll always have access to the sayHello.
Top comments (0)