DEV Community

Anoop P K
Anoop P K

Posted on

Factory functions with private variables in JavaScript

We all know classes in JavaScript , it is a template for creating objects.Classes are created using the "class" keyword in JS. But before the introduction of class we had an alternate way of achieving this object oriented approach - Factory Functions

Factory functions are simple javascript functions which returns an object

Factory function example

Note that we don't require a "new" keyword to create the object.

The "this" keyword used inside the function will refer to the execution context (environment in which the function is executed) of that function.

Now we have private variables in classes , Let us see how we can achieve this using factory functions.

We can make use of Closures in JavaScript. What is a Closure?
A closure is the collection of variables and functions that is being referenced.

The variables used inside a function cannot be accessed outside unless it returns the variable.

We can make use of these to simulate private variables using factory functions

Private variables using factory function

Here the variables id and marks cannot be used outside the function since it is block scoped. But it can be accessed by the inner function (status) , because it forms a closure with those variables.

References
Classes : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
Closures : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
Execution Context : https://www.freecodecamp.org/news/how-javascript-works-behind-the-scene-javascript-execution-context/

Top comments (1)

Collapse
 
taufik_nurrohman profile image
Taufik Nurrohman • Edited

The only drawback when returning anonymous object is that you cannot do comparison like this:

if (std instanceof Student) {}
Enter fullscreen mode Exit fullscreen mode

People in the past usually do this to allow function instantiation without the new keyword:

function Student(a, b, c) {
    if (!(this instanceof Student) {
        return new Student(a, b, c);
    }
    var marks = 0;
    this.status = function () { /* ... */ };
    return this;
}
Enter fullscreen mode Exit fullscreen mode