-1

Is there any way to use access the variable MyVariable from the StartPage class without using this.? The reason I am asking is that I need to reference this in a function, and this does not work there. I know from here that I could use => {... but that won't always work for me. How can I do this?

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-start',
  templateUrl: './start.page.html',
  styleUrls: ['./start.page.scss'],
})
export class StartPage implements OnInit {

  constructor() {}

  MyVariable = "Value";

  ngOnInit() {
   console.log(MyVariable); 
   //anyway to use MyVariable without `this.` prefix?
  }

}
isherwood
  • 58,414
  • 16
  • 114
  • 157
nachshon f
  • 3,540
  • 7
  • 35
  • 67
  • 1
    Does `bind(this)` work for you? – GCSDC Dec 18 '18 at 19:08
  • Have you tried passing it into `ngOnInit`? – isherwood Dec 18 '18 at 19:11
  • 3
    `The reason I am asking is that I need to reference this in a function` <= Could you share that code? Chances are you are just not binding `this` or you could be using a lambda but you were not aware how to. – Igor Dec 18 '18 at 19:12
  • Consider using `this`. Your team mates and future self will thank you. If you had trouble with a specific arrow function, please post the code for it and we can help. There should not be a case where an arrow function "doesn't work". – DeborahK Dec 18 '18 at 19:20

1 Answers1

3

I need to reference this in a function, and this does not work

I think this is because you tried to access from a callback function (subscription, setTimeout or similar) and this is not defined in the context. For having access to this as a reference of StartPage class, you must bind the reference to this to the function, for example:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-start',
  templateUrl: './start.page.html',
  styleUrls: ['./start.page.scss'],
})
export class StartPage implements OnInit {

  constructor() {}

  MyVariable = "Value";

  ngOnInit() {
     this.myFunction().bind(this);
  }

  myFunction(){
     // ...
     this.MyVariable = someValue
     // ...
  }

}
Diego N.
  • 562
  • 3
  • 10
  • Seems like that would work. But is there any other way to do this? Could I do something like `StartPage.MyVariable` ? – nachshon f Dec 18 '18 at 19:16
  • 1
    @nachshonf That syntax is how you access static variables. If you want to access an instance variable, you have to refer to an actual instance. – John Montgomery Dec 18 '18 at 19:18
  • @nachshonf `StartPage.MyVariable` would be something like a constant value, instead of a instance of the object itself. I can't tell if it could be done as far I know – Diego N. Dec 18 '18 at 19:19