Private State Utility

0.1.8 · abandoned · verified Sun Apr 19

The `private` package (version 0.1.8) provides a utility for associating truly private state with any JavaScript object, predating native private class fields. It achieves this primarily through two mechanisms: `makeAccessor`, which uses closures to create a secret object accessible only via a dedicated accessor function, and `makeUniqueKey`, which generates non-enumerable, unguessable property names. A crucial update in v0.1.2 addressed memory leak issues by ensuring secret objects are directly (but securely) stored on owning objects, allowing them to be garbage collected when the owner becomes unreachable. This package, last updated significantly years ago, is largely superseded by modern JavaScript features like private class fields (`#field`) but historically offered a robust solution for encapsulation in ES5 environments.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to associate truly private state with a JavaScript object using `makeAccessor`, preventing direct enumeration or access.

const getSecret = require("private").makeAccessor();

const user = {
  id: 'user-123',
  name: 'Alice',
  email: 'alice@example.com'
};

// Associate private data with the 'user' object
getSecret(user).passwordHash = "$2a$10$abcdefghijklmnopqrstuv.w.x.y.z";
getSecret(user).apiTokens = ['token-a', 'token-b'];

// Public properties are visible
console.log('Public user keys:', Object.keys(user)); // [ 'id', 'name', 'email' ]
console.log('Public user properties:', Object.getOwnPropertyNames(user)); // [ 'id', 'name', 'email' ]

// Private data is only accessible via the accessor function
const userData = getSecret(user);
console.log('User private data:', userData); // { passwordHash: '$2a$10$abcdefghijklmnopqrstuv.w.x.y.z', apiTokens: [ 'token-a', 'token-b' ] }
console.log('User password hash:', userData.passwordHash);

view raw JSON →