Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Make usages of "this" safe in class methods

    Basarat Ali SyedBasarat Ali Syed

    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.

    typescriptTypeScript
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss