Tutorial: Context or the "This" Keyword in JavaScript



I'm Adam Breindel and I teach classes with ProTech. I'm here to talk about context or the “this” keyword in JavaScrtipt. It's a small piece of the JavaScript language, but it's really important, and it hangs people up sometimes because it's a little counterintuitive how “this” works in JavaScript.

For background, JavaScript has a keyword "this," as do, C++, Java, C# and many other languages. The problem is that the JavaScript version works rather differently, and this is a source of pain and confusion for many JavaScript developers. Since it's an important part of the language, we should spend some time thinking about it.

01. Purpose and Problems with JavaScript's "This"

So let's take a look at where “this” came from, why we have it, what sort of problems can come up, and how we can fix them.

 

 

02. How JavaScript Decides What "This" Actually Is

 

 

Now that we've seen some of the problems that can come up with "this," that the "this" binding depends on how a function's called (not how a function's defined), let's dive into how the JavaScript runtime, or the browser, decides what the "this" binding" should be.

 

 

03. "This May Not Be What You Expected & How to Fix It

 

 

In this segment, we're going to look at another demo of the problem we just saw, and explain the problem of "losing context," or "losing the [desired] 'this' value." We'll look at several common workarounds, discuss the pros and cons of each, before moving on to a better solution. We also touch on browser compatibility implications.

 

 

04. Mastering "This:" Additional Techniques and Future Support

 

 

In this final section, we're going to look at an ECMAScript feature that makes it even easier to workaround the problem the way we were looking at it in the previous section. So, if we have to create a function inline, and preserve the value of "this," we can take an ECMAScript shortcut.

 

 

Conclusion

 

 

So, now we've looked at the definition of "this," how the browser decides what to bind "this" to, common problems that come up, workarounds, and the future of solving these problems.

Thanks for watching. If you're excited to keep diving into the details of JavaScript, I'd encourage you to check out ProTech's JavaScript Courses and Public Training Schedule.

Good luck with your JavaScripting.

Published January 8, 2014