1.1.0 • Published 7 years ago

create-internal v1.1.0

Weekly downloads
2
License
MIT
Repository
github
Last release
7 years ago

create-internal.js npm Travis CI Status

simple storage and access of private values, powered by WeakMaps

Example

const createInternal = require('create-internal');

// never export `internal`,
// as any code with access to it can access the "private" data within
const internal = createInternal();

class MyClass {
  constructor () {
    Object.assign(internal(this), {
      // accessible to code with this exact `internal` in scope
      privateProperty: 'value'
    });
    Object.assign(this, {
      // accessible to any code that can access the constructed object
      publicProperty: 'value'
    });
  }

  method () {
    const { privateProperty } = internal(this);
    // TODO: do something with privateProperty
  }
}

Usage

We use WeakMaps as the underlying store, which means that any value that is not a primitive type can be a key, e.g. Object, Array, Map, Set, Function, etc

createInternal()

returns a function that takes an object and returns a private object associated with it

const createInternal = require('create-internal');
const internal = createInternal(); // never export this

const publicObject = {};
const privateObject = internal(publicObject);
privateObject.privateProperty = 'privateValue';

createMapInternal()

returns a function that takes an object and returns a private Map associated with it

const { createMapInternal } = require('create-internal');
const internal = createMapInternal(); // never export this

const publicObject = {};
const privateMap = internal(publicObject);
privateMap.set('privateProperty', 'privateValue');

See Also