For more tips like this, sign up to the weekly newsletter!
Make an object callable
Some libraries offer objects that can be called like a function while also having some other properties. For example, ImmutableJs's List
can be constructed using both List()
and List.of()
.
How to make an object callable?
Let's say there is an Obj
, that has a property called of
, which is a function:
const Obj = {
of: () => {
console.log("Obj.of() called");
}
}
Obj.of(); // Obj.of() called
But what property to add to make Obj()
work?
Unfortunately, there is no real solution to this problem. Googling around, you can find a few hackish ones, but none without any problems or being overly complex.
Add properties to a function
But, as it turns out, reversing the problem makes it easy to solve. Don't try to make an Object callable, but add properties to a Function:
const Obj = () => {
console.log("Obj() called");
}
Obj.of = () => {
console.log("Obj.of() called")
}
Obj.of(); // Obj.of() called
Obj(); // Obj() called