Member-only story
Different ways to achieve encapsulation in JavaScript(ES6)

JavaScript is a powerful language full of different paradigms that let you write interesting and flexible code. However, at the same time it lacks some of the basic structural features the other languages have. By far one of the biggest anomalies of JavaScript is it’s inability to natively support encapsulation.
The scoping system was introduced with TypeScript, which is a superset of JavaScript. But unfortunately its not a clear victory yet since, while it does give you a warning, TypeScript code still compiles and runs even when you access the private variables.
Nevertheless, people came up with ways to achieve encapsulation using other features of the language. And in this post I’m going over the most widely used ones.
Easy way
The easiest way to achieve pseudo-encapsulation would be to prefix your private member with a special symbol that indicates the private scope to the client. It is a common convention to use the _
symbol as a prefix. Of course this won't actually prevent anyone from accessing your private variables so we won't go in too much detail here.
Factory functions and closures
Simply put, factory functions are functions used to create new instances of the object. Factory functions are often a preferred choice over the direct object creation using new
keyword. The reason is because using factory function gives you the freedom and flexibility to change the object's instantiation process without client ever being aware of the change.
Factory functions used with closures are often a go-to method for achieving encapsulation because of it’s simplicity. Let’s take a look at the example:
The code above is a typical example of attaining encapsulation via factory function and closure. While the implementation is pretty straightforward, it does come with a memory usage penalty. The reason is because method zoom
will be recreated for every new instance of…