Skip to content
jshacks.dev
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.

A class and a factory function can build the same objects, and the choice between them comes down to a handful of concrete differences. A class gives you new, instanceof, methods shared on a prototype and a standard way to extend one class with another, and it makes you live with this. A factory function is an ordinary function that returns an object: its private state is a variable in a closure, nothing can be reached from outside, and there is no this to lose, but each object carries its own copy of its methods and there is no built-in instanceof check or inheritance. Neither is more modern or more correct. This post builds the same counter both ways, compares them on private state, losing this, instanceof, methods and memory, inheritance against composition, serialization and testing, with exact output at each point, and finishes with a table for choosing. The examples run on Node.js 24.

The same counter, twice

JavaScript
class Counter {
  #count = 0;

  increment() {
    this.#count++;
    return this;
  }

  get value() {
    return this.#count;
  }
}

function createCounter() {
  let count = 0;

  const counter = {
    increment() {
      count++;
      return counter;
    },
    get value() {
      return count;
    },
  };
  return counter;
}

const fromClass = new Counter().increment().increment();
const fromFactory = createCounter().increment().increment();

console.log(fromClass.value, fromFactory.value);
console.log(fromClass.count, fromFactory.count, Object.keys(fromFactory));
Text
2 2
undefined undefined [ 'increment', 'value' ]

Both count to two. In both, the count itself cannot be read from outside: the class keeps it in a private field, marked with a hash sign, and the factory keeps it in a variable of the closure, which only the two methods can reach. The factory returns the object itself from increment and not this, which keeps chaining working even when the method is detached, as the next section shows. The class version needs new, and the factory is called like any function.

The problem with this

A method of a class uses this, so a method that is pulled out of its object and called alone fails. The factory methods use a closure and keep working.

JavaScript
const { increment } = createCounter();
increment();
console.log(typeof increment());

const instance = new Counter();
const { increment: detached } = instance;

try {
  detached();
} catch (error) {
  console.log(error.name);
}
Text
object
TypeError

The destructured factory method works, since it needs no this, and returns the counter. The class method throws, because this is undefined when a method is called without an object, and this.#count cannot be read from it. Passing methods as callbacks, to event handlers and promise chains, is where this bites, and a class needs an arrow function field or an explicit bind to avoid it. A factory has no such problem, as long as its methods do not use this.

instanceof

A class gives its instances an identity that you can test. A factory produces plain objects with no link to the function that made them.

JavaScript
console.log(fromClass instanceof Counter, fromFactory instanceof createCounter);
console.log(Object.getPrototypeOf(fromClass) === Counter.prototype, Object.getPrototypeOf(fromFactory) === Object.prototype);
Text
true false
true true

The class instance is an instance of Counter, and its prototype is Counter.prototype. The factory's object is a plain object, and instanceof against the function is false, since a function that is not a constructor has no usable prototype relationship with what it returns. If other code needs to ask "is this one of mine", a class gives it a way, and a factory needs a convention, such as a tag property or a symbol.

Where the methods live

A class puts its methods on the prototype, once, and every instance shares them. A factory that defines methods inside the function creates a new function for each method, for each object.

JavaScript
const a = new Counter();
const b = new Counter();
const x = createCounter();
const y = createCounter();

console.log(a.increment === b.increment, x.increment === y.increment);
Text
true false

The two class instances use the same function, and the two factory objects each have their own. For a few objects the cost is not worth thinking about, and for hundreds of thousands of objects with many methods the shared prototype uses less memory. A factory can share functions by defining them outside and passing the state in, at the price of losing the closure privacy.

Private state

Both can hide state, and by different mechanisms. A private field is part of the class syntax, and the language enforces it: reading instance.#count from outside the class is a syntax error, not a runtime failure. A closure variable is private because no other code has a reference to it. A subclass cannot see a private field of its parent, and code that gets the factory's object cannot reach the closure, and both are real privacy. The weaker option, a property named with an underscore, is only a convention and is no longer needed in either style.

Inheritance and composition

Classes extend each other with extends and super, and instances keep the chain, so a method not found on the subclass is found on the parent. Factories combine behavior by composition: build several small objects of behavior and merge them.

JavaScript
class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    return `${this.name} makes a sound`;
  }
}

class Dog extends Animal {
  speak() {
    return `${super.speak()}: woof`;
  }
}

const withSpeech = (state) => ({ speak: () => `${state.name} makes a sound: woof` });
const withName = (name) => ({ name });
const createDog = (name) => ({ ...withName(name), ...withSpeech({ name }) });

const rex = new Dog("Rex");
const fido = createDog("Fido");

console.log(rex.speak(), rex instanceof Animal);
console.log(fido.speak(), Object.keys(fido));
Text
Rex makes a sound: woof true
Fido makes a sound: woof [ 'name', 'speak' ]

The class version reuses the parent's method with super, and rex instanceof Animal is true. The factory version builds the object from parts, and nothing links it to a parent. Deep class hierarchies get hard to change, which is the reason that composition is often recommended, and a shallow hierarchy with one parent class is simple and clear. Choose based on whether your design is "is a" or "has".

Serialization

Private fields and closure variables do not appear in JSON. A class instance serializes its own enumerable properties, and the getters on a class are on the prototype, so they are not included. A factory object's getter is an own property of the object, and is included.

JavaScript
console.log(JSON.stringify(fromClass), JSON.stringify(fromFactory));
console.log(JSON.stringify(new Animal("Rex")), JSON.stringify(createDog("Fido")));
Text
{} {"value":2}
{"name":"Rex"} {"name":"Fido"}

The class counter serializes to an empty object, because its only state is private and its value getter lives on the prototype. The factory counter includes value, because the getter is a property of the object itself, and leaves out the method. If an object must survive being written to JSON and read back, give it an explicit toJSON, and rebuild it through a function that creates it from the data, whichever style you use.

Testing and replacing

A factory takes its dependencies as arguments, so a test can pass a fake without a framework, and the function that builds the object is the only place where parts are put together. A class can do the same through its constructor. The practical difference is mocking methods, which a class allows by replacing a method on the prototype or an instance, and which a closure does not allow, since the methods are fixed inside the function. Design for injection in both and the difference mostly disappears.

Choosing

You needPrefer
instanceof checks and a type identityA class
A hierarchy with shared behaviorA class with extends
Many instances sharing methodsA class
Real privacy with no thisA factory, or a class with # fields
Methods passed around as callbacksA factory, or arrow fields
Composition from small piecesA factory
Frameworks that expect classesA class
A few objects created by configurationA factory

Practical rules we follow

Use a class when the object has an identity and a lifecycle, and a factory when it is a bundle of behavior around some state. Use # private fields in classes. Do not use this in factory methods. Avoid deep inheritance. Give a class a static creation function if construction is complicated. And be consistent within a module.

Where this comparison stops

Both styles have a cost in tools: classes work with decorators, type checkers and frameworks that read the constructor, and factories work with plain functions that bundlers and tests handle easily. Neither affects speed in a way that decides the question for ordinary code. A factory can mimic a class by setting a prototype, and a class can mimic a factory with arrow fields, so the line between them can be blurred on purpose. The class syntax is documented on MDN.

Also inPatterns
Taggedpatterns
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.