I can’t seem to find the term for a function that acts like a class constructor – in that it creates new objects of a certain “shape” – but doesn't use the new
keyword, nor class
. (Is it a constructor function? It doesn’t have that keyword either!)
I've used both this pattern and classes in my code but realized I don't know how to describe the former.
An example of this idiom:
const makeCounter = () => {
let val = 0;
return {
increment() { val++; },
getVal() { return val; },
};
};
let aCounter = makeCounter();
aCounter.increment();
aCounter.increment();
console.log(aCounter.getVal()); //= 2
What should makeCounter
be called?
It's called a "factory function".
Factory functions usually return a object of a consistent type but are not instances of the factory function itself. Returned objects would rarely inherit from the factory function's prototype
property, and calling the factory function does not require new
before the function called.