Goal
Reach the "smartest" way of accessing this
inside a if
in a method of a JS class.
Description
In my case i'm talking about the the first two lines of the run
method and the last line of run
.
element.addEventlistener(this.listener, this.method)
doesn't work.
So i do for example const listener = this.listener
in the run
method.
Is there a way to avoid this?
Here is the whole class:
import GetElements from "./GetElementsByClassName";
export default class RegisterFunction {
constructor(className, listener, method) {
this.className = className;
this.listener = listener;
this.method = method;
}
run() {
const listener = this.listener;
const method = this.method;
const elements = (new GetElements(this.className)).findElements();
if (Array.isArray(elements) && elements.length > 0) {
elements.forEach(function (element) {
element.addEventListener(listener, method)
})
}
}
}