Javascript OOP Privacy levels

private members: Members that cannot be publicly accessed (Use Es6 weakMap with IIFE)
public members : Members do not use private members and that can be publicly accessed
privileged members: Members that use private members and that can be publicly accessed

Now here’s our example:

Every MacbookShop has its own private data customer list and stock

Whenever A shop sell a mac to customer, customers info will push to customer list and stock will minus 1

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Let’s take a look at how private member works!

When access to private members in the class, we may use IIFE + ES6 weakMap to achieve our goal instead just use function scope (in order to get private data in class we need to put Privileged members(privileged methods) in constructor, in this case will cause memory consuming issue)

In the example, IIFE provide an outer scope, we allow these two line access from prototype methods and inside constuctor:

Now every time we create a AppleShop, we add ourself (this) to the WeakMap Object as a key, and privateMember as value which is privateData.

Thanks to the IIFE scope, our prototype Privileged methods able to use _ function and pass ourself(this) to get privateMember variable.

This is how we can use ES6 and IIFE to achieve private member and privileged members without memory issue in Javascript.

Have a nice day!

Like what you read? Give Guan-Ting Jiang a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.