class TestClass {
constructor() {
this.prop = 5;
}
MethA() {
console.log(this);
console.log(this.prop);
}
MethB() {
(true ? this.MethA : null)();
}
}
Test = new TestClass();
Test.MethB();
Why does this code fail when reaching (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 preempt any further comments about the null
in what is clearly a demonstrative example:
In the real code, the condition of the ternary operator is a variable flag, and the false value is another method. The benefit to this structure is that the two functions can share a single argument list that only has to be written once and doesn't need a name.
No, moving the calls to inside the ternary operator doesn't answer this question. It loses the benefit of only needing to write the arguments once, and it's also side effect abuse.
The real solution is to replace the ternary with an if {} else {}
for side effects, or wrap the methods in arrow functions for a value expression. But that doesn't answer this question either: The point isn't what code could achieve a similar result, as that would be easy; The point is why this code doesn't work and what underlying language quirks are the cause of that.