Ishaan Shringi
Ishaan Shringi

Reputation: 183

Get instance of class (this) in function inside instance object - typescript/angular

I have a separate object that manages a particular dialog box. Consider the following code. As it is very easy to imagine what the functions do, I'm however unable to access the instance of the class. I tried using the traditional that = this approach.

export class Whatever implements OnInit {

    that = this;

    dialog = {
       data:{},
       open:function() {
           //way to access 'that' variable
       },
       close:function() {},
       toggle:function() {}
    }

    //other declarations and functions
}

As my application is scaling, I'm having too many functions inside this service. So i'm trying to club some of these functions into objects, which will make the code much cleaner.

Also if there is any better approach to this, I'd love to know. Thanks.

Upvotes: 2

Views: 3962

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074088

In your code, that isn't a variable, it's a property of the Whatever instance.

Your dialog is also a property of the Whatever instance. In calls to its methods, this will vary depending on how they're called.

To ensure they access the Whatever instance, you can use arrow functions and use this within the functions:

export class Whatever implements OnInit {

    dialog = {
       data: {},
       open: () => {
           // use `this` here
           // use `this.dialog.data` to acccess the data above
       },
       close: () => {},
       toggle: () => {}
    };

    //other declarations and functions
}

This works because class fields declared as you've declared them there are effectively initialized as though they were inside your constructor, and within the constructor, this refers to the instance. Arrow functions close over the this of the context where they're created (just like closing over an in-scope variable).

Upvotes: 0

abdullahkady
abdullahkady

Reputation: 1071

Best way would be to replace the function(){} with the ES6 arrow functions, which holds your this context like so () => {}.

You can also use functions(){}.bind(this), but it's much better to just use arrow functions. Both will keep your reference to this as expected in the body of the function

Upvotes: 6

Maksym Shevchenko
Maksym Shevchenko

Reputation: 746

You have to use arrow functions to not lose the context(this);

export class Whatever implements OnInit {   

  dialog = {
     data:{},
     open:() => {
         //'this' will point to Whatever class's instance
     },
     close:() => {},
     toggle:() => {}
  }

  //other declarations and functions
}

Upvotes: 1

Related Questions