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?
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));