Sunday, June 15, 2014

Which This?

If you’ve worked with JavaScript for while, you’ve likely been made aware of the unique power and confusion that comes with the “this” keyword. We’ve been using TypeScript in some of the single-page applications we’ve been working on, and it has a helpful syntax to help you manage the “this” keyword.

In each of these anonymous functions (lines 1 and 2 respectively) the keyword “this” (on lines 2 and 3) refers to the respective element that’s being iterated over (each div in the first function, each p in the second function.

However, using the => operator (sometimes called the “rocket ship” operator) when declaring the an anonymous function, changes the context of “this”.

Notice how the scope prior to the second (rocket shipped) anonymous function becomes accessible inside the anonymous function. This can also be used multiple times. E.G. If the parent TypeScript function had also been authored with the rocket ship syntax (() => {}) then the “this” keyword in all scopes would refer to the owner of the first function (the containing class or window object in this case).

Wrapping Up

As applications are becoming increasingly functional, the context in which anonymous functions are running becomes a more important tool for writing code. Knowing about some of TypeScrpt’s syntactic sugar helps us manage the “this” keyword without dropping down into JavaScript’s call, bind, and apply.

About Me

Tyler Holmes is a Solutions Architect working in Portland, Oregon. He lives mostly in the MS tech stack and is currently treading the waters of Communication/Collaboration and Business Intelligence with off the shelf/open source technologies.