1

This doesn't work:

-> f = Number.prototype.toLocaleString.call
<- ƒ call() { [native code] }
-> typeof f
<- "function"
-> f(1)
<- Uncaught TypeError: f is not a function
    at <anonymous>:1:1

Is it possible to reference and use some function's call "method" and use it as a regular function?

Armando Pérez Marqués
  • 5,661
  • 4
  • 28
  • 45
  • 1
    The `typeof f === "function"` really baffles me... – Armando Pérez Marqués Oct 24 '18 at 21:22
  • The `.call` property of *any* function is exactly the same as that of any other function. Also I don't get that error; I get a complaint that `.call()` is invoked with a `this` value that isn't a function (which is what I'd expect). – Pointy Oct 24 '18 at 21:24

2 Answers2

1

No, call is a method (inherited from Function.prototype.call) and like any shared method needs to be bound to its target if you want to use it as a plain function. In this case, the target object is the toLocaleString function:

const f = Function.prototype.call.bind(Number.prototype.toLocaleString);
console.log(f(1));
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

The problem is that any function's call property is equivalent to Function.prototype.call, which cannot be called on its own, without a calling context:

console.log(Number.prototype.toLocaleString.call === Function.prototype.call);

The solution is to explicitly give the newly created function a calling context of the original function, which can be done with bind:

const f = Number.prototype.toLocaleString.call.bind(Number.prototype.toLocaleString);
console.log(f(3333));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320