callable-object
Function call operators for JavaScript objects.
Motivation
The API can be cleaned up, but for now this is a proof-of-concept. Given an object and a function, return a proxy for the object that can be called like the function. Inspired by a TypeScript issue.
Related work
- callable-object
- callable-instance
- callable-instance2: This
might just be a republished copy of
callable-instance
. - invokable
- How to extend Function with ES6 classes?
Caveats
A proxy is not callable unless its target is
callable. To guarantee our
target is callable, we use a dummy function, which means we have to override
every proxy trap to redirect them to our real target object. We can use
Reflect
to help.
If we use a dummy function declared as a function or function expression, then
it will have non-configurable properties prototype
and arguments
that we
must include in our own
properties. If we use an arrow
function instead, it only has configurable properties name
and length
.
My implementation here works in JavaScript, but not in TypeScript. I don't know why.
If you have a method that returns this
, it will not return the proxy unless
you manage it yourself: store a reference to the proxy, return it instead of
this
, and initialize it with the proxy after constructing both the object
and the proxy.