Both build objects with private state and behaviour; they differ in where the methods live and how they find their state.
Factory function. A plain function that returns an object. State is a local variable, and methods are closures over the call's environment.
- Privacy is scope: nothing outside can reach the locals.
- Methods don't use
this, so they survive being passed as callbacks or destructured. - The function can return a cached object, a different implementation, or a composition of smaller objects, and callers don't need
new. - Cost: each call creates new function objects for every method, and there's no type to check with
instanceof.
Class. Methods are defined once on Class.prototype and shared by every instance; state lives in fields.
#privatefields are enforced by the language: access on an object without the field throws aTypeError, and#x in objis a brand check.instanceof,extends,superandstaticcome built in.- Methods read state through
this, so a detached method loses it. Calling a class withoutnewthrows.
How to choose (a judgement call; both are fine in modern code):
- Many instances, a real is-a hierarchy,
instanceofchecks, or an API built around subclassing (custom elements extendHTMLElement): class. - A few long-lived objects, methods handed out as callbacks, composition of capabilities, or construction logic you want to hide: factory.
Two corrections people miss: arrow-function class fields bring back per-instance functions, and #private is class-scoped, not instance-scoped, so one instance's methods can read another instance's #x, which closures can't do.