Keeping track of this
In JavaScript, the special variable this
is used to refer an object. But which object this refers too depends on the code you’re executing and how this
is used. So, a common problem for those learning JavaScript is keeping track of the value of this
in different situations. You can be happily testing your code, and then – bam! Suddenly, things stop working, and you’re wondering what happened, not realizing that you’re assuming this
is set to one value, when in fact, it’s an entirely different value. And, bugs caused by confusion about this
are notoriously difficult to track down.
Users posting asking questions about this
use the words “confused” and “baffled” a lot. In this installment of Head First JavaScript Programming Teasers, we take a close look at this
and how to keep track of it. You’ll learn how to know when this
is the global object (and what the global object is in the browser), how this
and the new operator work together, and common situations when it’s easy to lose track of this
, and how to fix your code if you’ve slipped on a this
banana peel.
Previous Head First JavaScript Programming Teasers Episodes
- Part 1: A Teaser from Head First JavaScript Programming
- Part 2: Getting JavaScript in your pages, the right way
- Part 3: What makes JavaScript different?
- Part 4: Dive into JavaScript
- Part 5: JavaScript variables and types
- Part 6: Using the console
- Part 7: JavaScript Scope
- Part 8: Working with the DOM