I am interested in creating a class that allows me to specify "For instance a1 of A, you will call the function computeValue() of a specific instance b1 of B when the value is needed". It's important for me to indicate which method of which instance will be utilized by this particular instance.
So far, I have discovered two potential solutions :
The eval()
approach :
class A {
constructor(funcToCall) {
this.funcToCall = funcToCall;
}
displayValue() {
console.log(eval(this.funcToCall));
}
}
class B {
constructor(value) {
this.value = value;
}
computeValue() {
return this.value;
}
}
var b1 = new B(1);
var a1 = new A("b1.computeValue()");
a1.displayValue();// Displays "1", okay
The function.call()
approach :
class A {
constructor(funcToCall, instanceToCallItOn) {
this.funcToCall = funcToCall;
this.instanceToCallItOn = instanceToCallItOn;
}
displayValue() {
console.log(this.funcToCall.call(this.instanceToCallItOn));
}
}
class B {
constructor(value) {
this.value = value;
}
computeValue() {
return this.value;
}
}
var b1 = new B(1);
var a1 = new A(b1.computeValue, b1);
a1.displayValue(); // Displays "1", okay
In my opinion, the eval()
solution seems messy while the function.call()
appears to be more organized.
Which approach do you think is superior? Are there any alternative and elegant ways to solve this problem?