@darkobits/private-data
v2.1.1
Published
A stopgap solution for private class data in JavaScript.
Downloads
14
Readme
This package provides a (temporary) way to achieve private fields (and methods) at runtime with JavaScript classes until the private fields proposal is finalized. It uses the Weak Map approach as outlined by Dr. Axel Rauschmayer's blog post on this topic.
This project is intended for academic purposes only and should not be used in production.
Install
$ npm i @darkobits/private-data
Use
This package's default export is a function that creates a new private data
store and returns a function which accepts an instance reference (re: this
)
and returns its private data object.
Parameters
|Name|Type|Description|
|---|---|---|
|context
|object
|Reference to a class instance, usually this
.|
Returns
object
- The instance's private data object.
Example
In this example, we will define a Person
class that uses private data. We will
use the variable $
for the data store.
import dataStore from '@darkobits/private-data';
const $ = dataStore();
class Person {
constructor(name) {
$(this).name = name;
}
getName() {
return $(this).name;
}
}
const frodo = new Person('Frodo');
frodo.getName(); //=> 'Frodo'
It is also possible to create "private methods":
import dataStore from '@darkobits/private-data';
const $ = dataStore();
class Person {
constructor(name) {
$(this).privateMethod = () => {
// ...
};
}
publicMethod() {
const result = $(this).privateMethod();
// ...
}
}
Caveats
- Private data is backed by an object in a Weak Map. Bear in mind that objects
in JavaScript are always passed by reference, so if you
return $(this);
, consumers of your class will have a direct reference to the instance's private data, which they can then modify at will. The same holds forreturn
-ing any sub-tree of this object. To avoid this, always return primitive values or clone non-primitives before returning them. - This module performs basic checks on
WeakMap.prototype.get
andWeakMap.prototype.set
to ensure they haven't been tampered-with, but a sophisticated attacker could subvert these checks.