Make usages of "this" safe in class methods

Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 years ago

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.

[00:00] 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.

[00:30] 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.

egghead
egghead
~ 40 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today