In Javascript, I would like to create a variable (primitive or object) that can also be invoked as a function.
The desired result is:
console.log(myVar) // Outputs some variable previously defined
console.log(myVar()) // Outputs the result of some previously defined function
I would like the variable used to be exactly the same. For example, I do not want:
const myVar = () => 1;
myVar.prop = 2;
I have tried overriding both the Object.prototype.toString and Object.prototype.valueOf functions, but each need to be manually invoked:
const myVar = () => 1;
myVar.toString = () => 2;
console.log(myVar + myVar) // This outputs 4, thanks to coercion
console.log(typeof myVar) // Outputs function, want 'number' in this example
My use case for this is the following scenario, where the result of someFunction(payload)
acts as both a value and a function.
someFunction(payload)(options) // Result depends upon payload and options, returns a value
someFunction(payload) // Options is not specified, returns a value
someFunction(payload, options) // Would prefer not to use this method
In the desired use case, I'd like someFunction(payload)
to act as an alias for someFunction(payload)()
. I tried:
const someFunction = payload => {
const innerFunction = options => {
// Return value depending on payload and, if it exists, options
};
innerFunction.toString = () => innerFunction();
return innerFunction;
};
console.log(someFunction(payload)(options)) // A value, correct
console.log(someFunction(payload)) // A function, do not want
I also tried using a combination of calling toString
and eval
(to executed the stringified function) to trigger the toString()
, but could not get it to work.