Trying to add function call operators to JavaScript objects.
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src
.gitignore
.prettierrc.toml
.travis.yml
LICENSE
README.md
package.json
tsconfig.json
tslint.json

README.md

callable-object

Function call operators for JavaScript objects.

code style: Prettier build status

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

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.