Was ist in JS Best Practice um eine Methoden-Referenz weiterzugeben? Speziell wenn man this als Kontext benötigt.
Habe mal 4 verschiedene Varianten ABCD. Bin mir aber noch unschlüssig, was davon wirklich das Beste ist.
class A {
constructor(data) {
this.data = data;
// Renamed for Example purpose: this.method = this.method.bind(this);
this.methodForB = this.method.bind(this);
this.methodForC = () => {
console.log(this.data);
}
}
method() {
console.log(this.data);
}
// Binding in Method
methodA() {
let f = this.method.bind(this);
this.execute("Method A", f);
}
// Binding in Constructor
methodB() {
let f = this.methodForB;
this.execute("Method B", f);
}
// Binding in Constructor direct as Arrow-Function
methodC() {
let f = this.methodForC;
this.execute("Method C", f);
}
// Arrow-Function and call in Method
methodD() {
let f = () => this.method();
this.execute("Method D", f);
}
execute(title, f) {
console.log(title);
f();
}
}
let instance = new A("data");
console.log("direct call");
instance.method();
instance.methodA();
instance.methodB();
instance.methodC();
instance.methodD();