In this article, we will cover how Object.create can be used for prototypal inheritance.
let's create an object using Object.create
In the above code snippet, we created a user object with one property and a function. Then we are passing that user object to Object.create and store the result in user1.
Can you guess what will be the output for the conole.log(user1) statement?
if you open the console you will see an empty object
But, if you expand that object, you will see a special property [[Prototye]] which has the user object properties and a bunch of other methods.
The user object that we pass to Object.create is set on the Prototype of user1 object.
Now, let's access the state property on user1
Here, user1.state will print "Delhi". First, state property is checked on user1, it is not found there. Then, it is checked on its prototype, it is found there, so it uses that.
let's verify that the state is not user1's property
In the above snippet, you can see user1.hasOwnProperty('state') returns false.
Now you must be wondering from where hasOwnProperty methods came. In javascript all objects eventually point to Object.Prototype
In our case chain is as follows
user1 Prototype => user Prototype => Object Prototype
hasOwnProperty is available on Object Prototype.
when we ran user1.hasOwnProperty('state'), it tried to find hasOwnProperty on user1, it is not found there. Then, it tried to find it on user Prototype, It is not found there as well. Then, it tried to find it on Object Prototype. It is found there.
you can see that the last two statements in the above code snippet return true
Now let's define state property on user1 and run console.log(user1.state)
In this case, state property is found on user1 itself, so it will not look any further.
Also when we run user1.printName(). The printName method is taken from the user1 prototype, as it is not defined on user1. But the state property is found on user1, so, it will be taken from there and not from its prototype.
If a property is not found on the object and also not found anywhere on the prototype chain, then undefined is returned.