0

In javascript I could use either saving this to function-scoped _this, or binding function to this directly (Function.bind or underscorejs bind utilites).

But typescript is supposed to more object-oriented, and I was expecting this in typescript to point to the class instance. But it does work just as in JS. So I have to use construction

    export class Mouse {
        private board : Presentation.View.Board;
        private focus : Presentation.View.Element = null;
        constructor(board:Presentation.View.Board){
            var _this = this;
            board.bindMouse(
                function(event:JQueryEventObject){
                    if( _this.focus ) _this.focus.move(event);
                }
            );
        }

or

    export class Mouse {
        private board : Presentation.View.Board;
        private focus : Presentation.View.Element = null;
        constructor(board:Presentation.View.Board){
            var _this = this;
            board.bindMouse(
                _.bind(function(event:JQueryEventObject){
                    if( this.focus ) this.focus.move(event);
                }, this);
            );
        }

So I ask, are there any ways to avoid direct this micromanagement? I suppose there is a way to make some kind of augumentations so class instance always have some reference to inself (it can have any name, like that).

1 Answer 1

1

Use the arrow functions. Form the spec:

A function expression using the function keyword introduces a new dynamically bound this, whereas an arrow function expression preserves the this of its enclosing context. Arrow function expressions are particularly useful for writing callbacks, which otherwise often
have an undefined or unexpected this.

 board.bindMouse((event: JQueryEventObject) => {
       if(this.focus) this.focus.move(event);
 });
Sign up to request clarification or add additional context in comments.

2 Comments

I really dislike this C-type syntax, but looks like its only good option.
That is strange, as I understand most developers like the arrow syntax.

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.