class Outer{
private outFunction(){
console.log("Okay!");
}
public functionWeCall(){
function innerFunction(){
this.outFunction(); //That doesn't work
}
}
}
I am trying to split the code into functions, for readability. But this doesnt work, how can I call an outer class function from an inner function?
-
1Probably the reason is the outFunction is private.Carlos Bazilio– Carlos Bazilio2020年09月04日 12:02:00 +00:00Commented Sep 4, 2020 at 12:02
-
2@Chaz a local function defined inside a member function is part of the class and therefore can access private membersUnholySheep– UnholySheep2020年09月04日 12:11:37 +00:00Commented Sep 4, 2020 at 12:11
-
1Privacy is also irrelevant. You simply have the wrong this.Aluan Haddad– Aluan Haddad2020年09月04日 12:46:57 +00:00Commented Sep 4, 2020 at 12:46
1 Answer 1
It's a matter of scope. When you get to functionWeCall(), this starts referring to that very function instead of to the class, thus outFunction() doesn't exist on this. A typical workaround might look like this:
class Outer {
private outFunction() {
console.log("Okay!");
}
public functionWeCall() {
let _this = this;
function innerFunction() {
_this.outFunction();
}
}
}
... but I'd rather advice reworking the whole thing so that you don't have nested functions like that.
Edit: as suggested by @Aluan Haddad, here's the same thing, but with an arrow function:
class Outer {
private outFunction() {
console.log("Okay!");
}
public functionWeCall() {
() => {
this.outFunction();
}
}
}
... and if you want the inner function to still be callable, 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()
}
}
3 Comments
this, you commonly need to create functions that close over this, i.e. to pass to some other function, and such functions are by definition nested.=>, were added to JavaScript because this is a common annoyance. Arrow functions don't have their own this so you can use it like you would any other variable inside one.