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

 

Don't miss out!!

Don't miss out on brain-friendly WickedlySmart updates early access to books and general cool stuff! Just give us your email and we'll send you something about once a week. 

You have Successfully Subscribed!