Check out a free preview of the full Deep JavaScript Foundations, v3 course:
The "this Exercise" Lesson is part of the full, Deep JavaScript Foundations, v3 course featured in this preview video. Here's what you'd learn in this lesson:

Students are instructed to refactor existing code to use the namespace pattern.

Get Unlimited Access Now

Transcript from the "this Exercise" Lesson

[00:00:00]
>> Kyle Simpson: Let's jump into the this keyword, and try to understand it a little bit better through code. Let's write some code in this exercise. In this exercise you're gonna be refactoring some code that currently uses the module pattern, and you're gonna instead make it use that namespace pattern where you have methods on an object and they refer to the data properties on that object using the this keyword.

[00:00:23] So if we look at the ex.js you'll notice that we have our module definition. We've got this defineWorkshop() function, which is our factory function. It's producing this publicAPI object and it has these internal things, these internal data values, like currentEnrollment and studentRecords. What we wanna do is turn the deepJS from being defined by a function to being defined as an object literal that has properties that reference the currentEnrollment and studentRecords.

[00:00:53] And all of those functions, instead of being hidden, they'll all be public methods on that object and they'll all make references with this stop. A word of caution, that there are a bunch of places within this code. For example, we pass in a callback like this one right here.

[00:01:12] We pass in this callback to .map. When it’s a regular lexical function, the way it is in the module pattern, no problem whatsoever. But when we pass in this to where functions, we have the problem of our this binding. So you need to make sure to watch out for the places where you need to pass in hard-bound references to the methods, okay?

[00:01:33] So the readme will give you the instructions on taking out the defineWorkshop() factory, replacing it with an object. Change all those internal references and make sure that you use the bind where it's needed, but don't use the bind on everything because it's not needed for all of the function calls.

[00:01:52] As always, if you get stuck and need some help, make sure to look at the solution file, the ex.fixed. We'll be back in a few minutes to talk through the solution.