setec
setec

Reputation: 16090

"This" in Typescript class instance

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).

Upvotes: 0

Views: 216

Answers (1)

krlm
krlm

Reputation: 837

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);
 });

Upvotes: 1

Related Questions