Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 985 of the free egghead.io lessons, plus get TypeScript content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Make usages of "this" safe in class methods

0:59 TypeScript lesson by

this is determined by how you call a function. To write class methods that can always safely use this you can use the TypeScript property initializer syntax along with arrow functions.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

this is determined by how you call a function. To write class methods that can always safely use this you can use the TypeScript property initializer syntax along with arrow functions.

Let's create a simple TypeScript class with the property name and a method log which logs this.name to the console. Now if you go ahead and create an instance of the class and call the log method on the instance, you can see that it works fine. However, if you go ahead and call the log method on its own without accessing it out of the class instance, you'll see that this no longer is valid within the function. The reason is that this is determined by how you call the function.

Class methods that use this work fine only as long as they are called on an instance of the class. Thanks to TypeScript you can fix it easily by converting the class method into a class property that uses a property initializer syntax to initialize the property to an arrow function. Now all uses of this in the property are safe, because the arrow functions ge to this from the lexical scope, which in the case of the class property is always a class instance that contains the property.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?