privates

1.0.1 • Public • Published

privates

JavaScript doesn't provide any language-level means to make object properties private. This Node module:

  1. Allows you to associate pseudo-private arbitrary key/value pairs with any object without polluting its properties.
  2. Minimizes memory overhead by using WeakMaps, which allow keys to be garbage collected once they're no longer referenced.
var privates = require('privates');
 
var obj = {x: 1};
privates.set(obj, 'y', 2);
 
assert.equal(obj.y, undefined);
assert.equal(privates.get(obj, 'y'), 2);

Usage

Install it with npm:

npm install privates

Then require it like so:

var privates = require('privates');

The module exports the following methods:

set(owner, key, value)

Creates a private key/value pair associated with the owner object.

Note: The key will always be coerced to a string, because the internal map for each owner object is simply an Object literal.

privates.set(obj, 1, 'foo');
privates.get(obj, '1'); // === 'foo'

get(owner, key)

Returns the value of named key associated with the owner object by calling set(owner, key).

delete(owner, key)

Deletes the value of named key associated with the owner object.

deleteAll(owner)

Removes all of the values associated with the owner object.

Readme

Keywords

Package Sidebar

Install

npm i privates

Weekly Downloads

2

Version

1.0.1

License

CC0-1.0

Last publish

Collaborators

  • shawnbot