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?

Upvotes: 1

Views: 39

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 371069

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

Upvotes: 1

Bergi
Bergi

Reputation: 665276

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

Upvotes: 1

Related Questions