Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function within Class accessing 'this'

Tags:

typescript

This is a very basic example of the function I'm trying to achieve. My problem is that when calling 'greet', appConfig will not exist on 'this' since it's inside the function.

How can I maintain access to the outer 'this' and be able to call appConfig? I'm hoping to do this without assigning the outer 'this' to some variable like self.

class Greeter {
	
	static $inject = ['appConfig'];
    constructor(
		private appConfig: any
	) {
    }
	
    greet() {
        return getMessage();
		
		function getMessage() { 
			return this.appConfig.value;
		}
	}
}
like image 214
mrshickadance Avatar asked Dec 15 '25 15:12

mrshickadance


1 Answers

You can use arrow functions instead. They inherit the closure's context.

class Greeter {

  static $inject = ['appConfig'];
  constructor(
    private appConfig: any
  ) {}

  greet() {
    let getMessage = () => this.appConfig.value;

    return getMessage();
  }
}

You can read more on arrow functions here.

Although in this case I would recommend you just make another private method in the class and call that.

class Greeter {

  static $inject = ['appConfig'];
  constructor(
    private appConfig: any
  ) {}

  greet() {
    return this.getMessage();
  }

  private getMessage() {
    return this.appConfig.value;
  }
}
like image 67
toskv Avatar answered Dec 17 '25 11:12

toskv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!