Blog>
Snippets

Protecting Private Properties with Object.defineProperty

Utilize Object.defineProperty to encapsulate 'private' object properties by not exposing them to enumeration.
// Function to create a 'private' property
function createPrivateProperty(obj, propName, value) {
  Object.defineProperty(obj, propName, {
    value: value,
    writable: true,
    configurable: true,
    enumerable: false // This ensures the property is not enumerable
  });
}

// Example usage
const person = {};
createPrivateProperty(person, '_age', 30);
This code snippet defines a function 'createPrivateProperty' that takes an object, a property name, and a value, then it defines a new property on the object with 'Object.defineProperty'. The property is made non-enumerable by setting 'enumerable' to false, which effectively makes it 'private' as it won't show up in enumerations like for...in loops or Object.keys().
// Adding a public method to access the private property
person.getAge = function() {
  return this._age;
};

// Example of trying to enumerate properties
for (let prop in person) {
  console.log(prop); // Only outputs 'getAge', not '_age'
}
This code snippet adds a public method 'getAge' to the person object to allow controlled access to the 'private' _age property. It then demonstrates enumerating over the 'person' object's properties, showing that the '_age' property is not enumerated as it is not enumerable.