Link to Other Objects through the JavaScript Prototype Chain

Tyler Clark
InstructorTyler Clark
Share this video with your friends

Social Share Links

Send Tweet

Objects have the ability to use data and methods that other objects contain, as long as it lives on the [[prototype]] chain. In this lesson we’ll test this out by adding properties and working with this linkage of properties.

Instructor: [00:01] Objects in JavaScript give us the ability to create key and value pairs. In this example, we've got an object here called object with the first name property. We console.log first same. We see that we get Tyler.

[00:13] As you probably expect, if we were to look up a property that did not exist on our object, we'll get an undefined back, which is true for all cases where the property is not on the object, unless that property lives somewhere on the prototype chain.

[00:27] For example, if we remove last name and replace it with a two-string method, you can see that we no longer get undefined, but an actual return value. This is because the property of two string lives in an object that is connected to this object somewhere through the prototype chain.

[00:45] We can use the Google DevTools to see this relationship a little bit clearer. If we console.log in here, we can see our object but then there is also this link to another object. This is what is considered the prototype chain.

[00:59] In JavaScript, when the object's literal form is used -- as we did in this case -- the prototype chain is linked to the global object's prototype object. It is here where we are able to get the two-string method. Use it inside of our code without it returning undefined or throwing an error.

[01:19] Now, let's create a new object called proto object. We'll give it the property of last name, with the value of string of clerk, then we'll say object.setPrototypeOf(object) as prototype object.

[01:32] As the name suggests, we are setting the prototype or the next inline chain object of object to be proto object. Now, if we remove the two-string property and change it to last name, we'll see that we get clerk.

[01:47] Again, the only reason why we get last name on the object here is because proto object has been set as the prototype of object. We can see this relationship better by pasting this into our browser.

[02:06] Now, if we open up object, we see that this next inline object is our proto object that we created. Keep in mind that when we go back to the two-string method, we still have access to it. Our JS engine will continue on through object-after-object until it reaches the end of the chain.

[02:26] For the two-string method, when we look it up on our object, our engine will go through object-by-object and find it here at the end.