Search code examples
javascriptfunctionfunctional-programmingfirst-class-functions

Is it possible to use a reference to some function's call attribute and pass it around as a value?


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?


Solution

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