Check out a free preview of the full JavaScript: The Hard Parts of Object Oriented JavaScript course:
The "Avoid Duplication with Prototype" Lesson is part of the full, JavaScript: The Hard Parts of Object Oriented JavaScript course featured in this preview video. Here's what you'd learn in this lesson:

Will introduces the next problem to be solved, which is refactoring the previous solution into one that uses object.create to create objects, but still has access to the functionality.

Get Unlimited Access Now

Transcript from the "Avoid Duplication with Prototype" Lesson

[00:00:00]
>> Will Sentance: The problem with this approach is, fundamentally, each time you create a new user, we make space in our computer's memory for all of our data and functions but our functions are just copies. Our data's unique, the data's unique, but our functions are just copies. Is there a better way?

[00:00:14] Yes, there is. Benefits, it's fundamentally at least simple to reason about. At no point is it mysterious where my increment function was. It was right there on the object. So it was easy to reason about, but it is untenable. So instead store the functions we want our user 1, user 2, user 3, user 500 to have access to.

[00:00:37] Store them on a single object, and have JavaScript go look up there. How do we do this? How do we make that link? Yeah, prototype. Prototype chain, exactly. Using the prototype chain have a separate, I don't know, object in which we have a function like increment stored. And when we call user1.name on the user one object, yeah, no problem, it's there.

[00:01:00] But when we call user1.increment rather than go, error increment is not there, somehow link user1 up to the function store object. That's our goal. Make this link, well, there's a number of ways we can make it, but the way we're gonna make it is using object.create. So we're gonna rebuilt our solution one into solution two to generate objects, user 1, user 2, that still somehow have access to this function.

[00:01:25] And remember, I'm gonna say it again and again and again, the only goal we have in object oriented programming is, can we bundle up the appropriate and relevant functionality with the relevant data that it applies to? Not have to go hunt off on another part of our file for a particular function, but just bundle them up together.

[00:01:47] Can we do that? That is our fundamental goal. All right, so we're gonna walk through this code and actually, I'm just gonna tell you right now, folks, this code here is gonna turn out to be highly effective. And actually gonna be the approach that answers the question, one of the most popular senior dev questions in JavaScript.

[00:02:09] This approach, people, is gonna turn out to be answer to, how does the new keyword work under the hood? One of the most popular senior JavaScript developer questions out there. And we are going to answer that question right now.