What is __proto__? | JavaScript
Inam Ul Haq
Posted on June 7, 2019
You'd probably notice this __proto__
property every time you log an object
into the developer console.
In this post, I'm gonna try to explain where this __proto__
comes from, what it contains, and anything in between. So, let's get this __proto__
.
First, let's understand how a JavaScript object
gets constructed. Once you understand how an object
gets constructed, __proto__
property is gonna make a lot more sense than otherwise.
How an object
get constructed?
A JavaScript object
, always, get constructed/produced by a constructor function. Now, you'd probably say "But, object literals? They are not constructor functions."
Well, object literals are just syntactic sugar. You can write objects without using object literals. See the example below, both syntax would produce the same output. The second approach gives us more power(which we won't discuss here) which object literal takes away from us.
// an object using object literal
const person = {
name: "John",
age: 30
};
// an object using Object constructor function
const person = new Object();
Object.defineProperties(person, {
name: {
value: "John"
},
age: {
value: 30
}
});
Now that we know that every object
, in JavaScript, is constructed by a constructor function, let's get back to the original question.
What is __proto__
?
__proto__
is a property, in every JavaScript object
, which points to object
's constructor function's prototype
property. I know it's a bit hard to grasp, but let me simplify it for you.
Every constructor function has this prototype
property on them. The picture below shows us Object
constructor function's prototype
property.
So, every object
, we'd construct/produce from Object
constructor function, would have __proto__
property pointing to Object
constructor function's prototype
property.
Example
When we use object literals, as we did in the example below, Object
constructor function is used to construct/produce the object. Now that we have a person
object constructed/produced from Object
constructor function, we can verify that __proto__
from our person
object is same as prototype
from Object
constructor function.
// an object using object literal
const person = {
name: "John",
age: 30
};
// verify
console.log(person.__proto__ === Object.prototype); // true
If you didn't understand something from the post, or I missed something, please, let me know.
This is my first ever blog post and I'm open to criticism/suggestions.
Posted on June 7, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 17, 2024