Skip to content

shawnbot/privates

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.

About

Pseudo-private variables for JavaScript

Resources

Stars

Watchers

Forks

Packages

No packages published