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
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
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)
The only drawback when returning anonymous object is that you cannot do comparison like this:
People in the past usually do this to allow function instantiation without the
new
keyword: