class TestClass {
constructor() {
this.prop = 5;
}
MethA() {
console.log(this);
console.log(this.prop);
}
MethB() {
(true ? this.MethA : null)();
}
}
Test = new TestClass();
Test.MethB();
What is the reason for the failure of this code when trying to access this.prop
in MethA
from the ternary operator in MethB
?
VM:6 undefined
VM:7 Uncaught TypeError: Cannot read property 'prop' of undefined
at MethA (<anonymous>:7:26)
at TestClass.MethB (<anonymous>:10:35)
at <anonymous>:14:6
To address any potential comments regarding the inclusion of null
in this illustrative example:
In actual code, the condition of the ternary operator is a variable flag, with the false value being another method. This structure allows two functions to share a common argument list that only needs to be written once and doesn't require a name.
No, moving the calls inside the ternary operator does not fully resolve this issue. It sacrifices the benefits of writing arguments only once and may lead to side effects.
The true solution would involve replacing the ternary operation with an if {} else {}
for side effect purposes or wrapping the methods in arrow functions for a value expression. However, neither of these solutions fully addresses the root cause of why this code fails to work due to underlying language quirks.