I have encountered with something like this:
class Example {
// ...
async #privateMethod() {
return true
}
static staticMethod() {
try {
// can't access #privateMethod
this.#privateMethod()
} catch (error) {
console.log('error', error);
}
}
}
I want to call a private method within the static method, but I can’t access the private method for some reason. What am I doing wrong, please?
2
Answers
In a static method there is nothing like this. This is the instance of an class created with
And then you call the methods with
In this method you can then use this as a pointer to the myClassInstance.
A static method is called without such an instance so you have no this and so you can’t call non static methods.
That private method is an instance method, meaning you would need
this
to be an instance ofExample
to dothis.#privateMethod
.When running a static method, you don’t have an instance. Instead,
this
refers to the constructor (the "class").This may be an indication that
#privateMethod
shouldn’t be an instance method after all, as it could do its job without one.If this is the case, then just make that private method also static: