When you reach the functionWeCall()
function, this
starts pointing to that specific function rather than the class itself. This means that outFunction()
is not accessible through this
. One common workaround involves utilizing a variable like this:
class Outer {
private outFunction() {
console.log("Okay!");
}
public functionWeCall() {
let _this = this;
function innerFunction() {
_this.outFunction();
}
}
}
However, it may be preferable to reconsider the structure to avoid nested functions like this.
Edit: In response to suggestions from @Aluan Haddad, here is the updated approach using an arrow function:
class Outer {
private outFunction() {
console.log("Okay!");
}
public functionWeCall() {
() => {
this.outFunction();
}
}
}
If you still want the inner function to be callable, you can assign it to a variable:
class Outer {
private outFunction() {
console.log("Okay!");
}
public functionWeCall() {
let innerFunction = () => {
this.outFunction();
}
innerFunction(); // this could be anywhere in the scope of functionWeCall()
}
}