Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    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.



    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




    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.