I need to execute a random function in my code. Here is what I have:
module A {
...
export function foo(): number {
let b = new B();
let possibleFunctions = [
b.possibleFunction1,
b.possibleFunction2
];
let index = Math.floor(Math.random() * 2);
possibleFunctions[index](_var_);
}
class B {
public usefulFunction() {
console.log("bbbb");
...
}
public possibleFunction1() {
...
console.log("aaaa");
this.usefulFunction();
console.log("cccc");
}
public possibleFunction2() {
...
}
}
}
The program only seems to output "aaaa" and the usefulFunciton()
is never called, resulting in an error.
When I replace
possibleFunctions[index](_var_);
with
possibleFunction1(_var_);
everything works as expected.
This led me to wonder:
1. Is my observation accurate?
2. If so, why does it happen? Is the function deep-copied somehow?
3. What is the correct approach to resolve this?
Thank you!