4

In TypeScript, if you define a function using () => {...}, the this variable will refer to the instance of the surrounding class. But if you use function () {...}, the this variable will have its old JavaScript interpretataion.

Is there any way to access both of these this variables within a TypeScript function?

I occasionally need this when using JQuery in TypeScript:

class X {
    private v : string;
    constructor() {
        $('.xyz').on('change', function() {
            this.v = $(this).prop('value'); // Two different this's
        })
    }
 }

In the central line in the code, the first this should refer to the class X object, whereas the second this should refer to the JQuery object that triggered the event.

1 Answer 1

6

In the change event handler this will refer to the .xyz element that raised the event only. If you want a reference to the containing X class then you need to store a variable holding that reference, like this:

class X {
    private v : string;
    constructor() {
        var _x = this;
        $('.xyz').on('change', function() {
            _x.v = $(this).prop('value'); 
        })
    }
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.