Data Protection in OOPs

Introduction to data protection in constructor functions and classes in JavaScript by hiding or preventing access to properties.

Background

Now that we know about constructor functions, classes, and how they achieve OOPs, let’s focus on security. At times, it is important for properties to be hidden or stay inside of an object. We can achieve this data encapsulation through two approaches. Let’s check them out.

Hiding properties

Up until now, all constructor function and class properties were easily accessible outside of it and their values could be modified without any restrictions. In JavaScript ES5 and ES6, there is no formal support for access modifiers using keywords such as public, private, or protected which are keywords used by other languages. By default, all properties are public so they can easily be accessed. Our goal is to define internal properties.

Internal property is a property or method that can only be accessed by methods inside the constructor function or class.

Get hands-on with 1200+ tech skills courses.