As far as I know the suggestions of private fields/functions of classes came with ES2019 with the # syntax.
I have the following class for example:
class MyClass {
#firstPrivateMethod(parameter) {
// method functionality.
}
#secondPrivateMethod(parameter) {
var someValueFromTheOtherMethod = this.#firstPrivateMethod(parameter);
}
constructor() {
var firstPrivateMethod = this.#firstPrivateMethod;
var secondPrivateMethod = this.#secondPrivateMethod;
window.onresize = function() {
this.#firstPrivateMethod = firstPrivateMethod; // <-- error: Cannot write private member #firstPrivateMethod to an object whose class did not declare it.
secondPrivateMethod(parameter);
}
}
}
I'd like to temporarily pass the private methods and fields of my class to the event handler's this object then later i'd remove these event handlers or set them to null after they finished a certain class-based task.
The reason why i need this is that my class is attaching elements to the DOM and the style of these elements are calculated from it's dependencies. I think it would be really hard or impossible to make it responsive with media queries. I have some breakpoints for different devices. After every breakpoint i'd drop the attached elements then i'd change the values of the dependencies and re-attach them with the new style.
At first i had an idea. I tried to modify my code like this:
class MyClass {
#firstPrivateMethod(parameter) {
// method funcionality.
}
#secondPrivateMethod(firstPrivateMethod, parameter) {
var someValueFromTheOtherMethod = firstPrivateMethod;
}
constructor() {
var firstPrivateMethod = this.#firstPrivateMethod;
var secondPrivateMethod = this.#secondPrivateMethod;
window.onresize = function() {
secondPrivateMethod(firstPrivateMethod, parameter);
}
}
}
But it got me nowhere because my code got so messy that it was really hard to read.
Do you have any idea how to solve this problem?