DEV Community

Cover image for Classes vs Factory functions in Javascript
Snevy1
Snevy1

Posted on

Classes vs Factory functions in Javascript

Between Factory Functions and Classes which is better?

In Javascript, you can arrange your code using object oriented patterns such as factory functions, classes and constructors.Choosing the right pattern can be tricky. In this article, I will explain what classes, constructors and factory functions are and how to use them in various situations.

In my previous article, I discussed extensively how creating objects by classes and constructors is better than object literal.Check it out here.

Classes in Javascript

If you know constructors then classes shouldn't be hard to grasp. Classes are a syntactic sugar of constructors in Javascript.

The code below shows a constructor function.

function playerCreator(name, score) {
  this.name = name;
  this.score = score;
}

playerCreator.prototype.increment = function () {
  this.score++;
};
playerCreator.prototype.login = function () {
  this.login = false;
};
Enter fullscreen mode Exit fullscreen mode

Notice how the increment and login functions are placed on the prototype.They are shared functions so any object created by the constructor has access to the methods. This saves memory.

This next code shows a class object.


class playerCreator{

  constructor(name,score){
   this.name = name;
  this.score = score;
  }

increment: function () {
  this.score++;
};

login:  function () {
  this.login = false;
};



}
Enter fullscreen mode Exit fullscreen mode

When we create a class object we start with the keyword class then a function name. Inside of the function we add a constructor that holds the parameters to be used. Notice that instead of adding increment and login methods on the prototype explicitly, we nicely tuck them inside the class object though under the hood they are added to the prototype(implicitly)

So if constructors and classes do essentially the same thing why should we use classes instead of constructors?

Classes are easy to read.

By using classes, Javascript tries to follow the normal convention of object-oriented programming, though it is still a prototypical-based language.

Also, classes are not native to JavaScript but are widely used in other object-oriented programming languages such as C# and Java. To avoid confusion that developers from these languages face when they encounter Javascript, classes are a better solution.

Factory Functions

Factory functions in javascript

What are factory functions? Factory functions are functions that return a new object. They are quite similar to classes, but they utilize the power of closures in that, they don't use the new keyword.

Once you call the function, it sets up and returns a new object.

Below is how we would implement a factory function:

function playerCreator(name, score) {
  return {
    name: name,
    score: score,
    increment() {
      return (this.score += 1);
    },
    login() {
      return (this.login = false);
    },
  };
}

let player1 = playerCreator("John", 8);

player1.increment(); // 9
Enter fullscreen mode Exit fullscreen mode

Benefits of using Factory Functions over Classes in javascript

  • There is no use of this keyword when instantiating variables. It is only used inside methods. This reduces the confusion of the this keyword.
  • There is no use of the new keyword which is often forgotten when creating objects using classes.
  • It is easier to setup since it looks quite similar to regular functions.
  • Simplicity - Factory functions provide a more straightforward and flexible way to create objects. They don't have the syntactic complexities that come with class declarations and prototypes, making them more approachable for developers who prefer a simpler syntax.

  • Encapsulation with Closures: It is easy to encapsulate private variables and objects with Factory functions since is natural to them.This enhances data privacy and abstraction.

Benefits of using Classes over Factory functions in Javascript

  • Classes save memory so they are suitable when creating large applications that require creation of thousands of objects.
  • Classes are used in many programming languages hence it is a cleaner way to follow object oriented programming paradigm.
  • Inheritance: Classes support the concept of inheritance, making it easier to create a hierarchy of objects. You can use the extends keyword to create a subclass that inherits from a superclass.
class Student extends Person {
  constructor(name, age, grade) {
    super(name, age);
    this.grade = grade;
  }

  // Additional methods or overrides
}

const student1 = new Student('James', 18, 'A');

Enter fullscreen mode Exit fullscreen mode
  • 'instanceof' Operator: Classes make use of the instanceof operator, which can be useful for type-checking and determining if an object is an instance of a particular class.
console.log(student1 instanceof Student); // true
console.log(student1 instanceof Person);  // true

Enter fullscreen mode Exit fullscreen mode

Conclusion

The choice between classes and factory functions depend on your specific needs and which pattern you are comfortable with.

In my opinion, factory functions are great and the performance benefit of classes is minimal. Let me know your opinion in the comments below.

Follow me on:

Twitter

Linkedin

Top comments (0)