This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Catch unsafe use of "this" in TypeScript functions

    Basarat Ali SyedBasarat Ali Syed

    this is probably the most tricky thing to use in JavaScript and therefore TypeScript. Fortunately there is a TypeScript compiler flag noImplicit this that can help catch unsafe usages so beginners don't get caught off guard.

    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 Here I have a simple function, fu, which logs this to the console. If I go ahead and call this function from the root of the file, you can see that this actually points to the node js global variable. I can prove this by simply checking if this is equal to global, and it is.

    00:19 Now if I go ahead and create a bar variable that has fu as a member and now call bar.fu, you can see that within the function this will no longer point to the global variable and instead it points to bar.

    00:35 This is because for simple functions, in JavaScript and TypeScript the value of this changes based on how the function is called. This is why there is a TypeScript compiler option called noImplicitThis.

    00:49 As soon as you set that to true, any unsafe usages of this immediately become errors. If you still want the unsafe behavior, you are free to annotate this as any for a given function and you can see that the errors go away.

    Discuss

    Discuss