simple storage and access of private values, powered by WeakMaps
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
}
}
We use WeakMap
s 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
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';
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');