JavaScript encapsulation & the module pattern

Encapsulation is one of the key features of object oriented programming languages. In languages like Java, it is very straight forward concept to implement. Since I know JavaScript is considered an OO language, I decided to try to understand once and for all how to implement encapsulation in JavaScript correctly. Let’s say we have a function with one private field and one public field: Try It The fields are of course undefined since we need to call f1() in order for them to have values. Now let’s create an object from that function: Try It After instancing, x and y both have values, but of course, only y is public. Now lets encapsulate field x. Try It This is the most basic encapsulation and it works. But this approach has a problem, f1() is in fact a kind of constructor. Whenever an instance will be created than the getter method will also be created. This approach is not the preferred way to create methods in JavaScript. The preferred approach in JavaScript is to create the methods attached to the prototype. In this way they will only be created once. But this approach also has a problem, we cannot use it Continue reading JavaScript encapsulation & the module pattern