0

Treating the bind method for JS functions as a value makes it behave unexpectedly when used in conjunction with both the ternary and short-circuit operators. Why does this happen?

I tried to make a utility function shorter by using the ternary operator, but it always resulted in Uncaught TypeError: Bind must be called on a function.

So I tried this that worked just fine:

(Date.bind)(null)()

Nevertheless this did not:

(true && Date.bind)(null)()

Neither did this:

(true ? Date.bind : '')(null)()

As per the evaluation of those expressions I expected the same output on each one—a string value representing a date—but it just happened in the first one and the other ones resulted in the error Uncaught TypeError: Bind must be called on a function.

septum
  • 11
  • 4
  • 1
    It's *any* operator (but the grouping operator) that makes the property reference loose its context. It's like `const bind = Date.bind; bind(null)()` which you wouldn't expect to work either, right? – Bergi Jan 16 '19 at 21:41
  • I hope the duplicate answers explains everything you asked for. If not, please comment and I'll reopen. – Bergi Jan 16 '19 at 21:44
  • Yes, that would not work. So the only option I have is to immediately call `Date.bind` so that maintains its context? – septum Jan 16 '19 at 21:51
  • Thanks, it answered my question and shined a new light on it. No reopening is necessary. – septum Jan 16 '19 at 22:06
  • Yes, either invoke `bind` immediately as a method, or later `.call(…)` it on `Date` (i.e. `bind.call(Date, null)`), but that's probably not what you'd want :-) – Bergi Jan 17 '19 at 10:42

0 Answers0