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;
}
}
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With