Private fields in Javascript
This NPM module can be used to associate private data with objects.
It stores an associated object with the private data in a WeakMap,
keyed on the subject. If the subject is garbage collected, so is the private data.
This module works in Node JS (v4 and up) and all browsers that have support for WeakMap (all modern browsers).
npm install --save prv
const createAccessor = require('prv')
const prv = createAccessor()
// or, shorthand
const prv = require('prv')() // <-- note the double braces
import createAccessor from 'prv'
const prv = createAccessor()
Since this module is super-small, it might be beneficial for
you to just copy-paste it into your codebase verbatim:
const createAccessor = () => {
const p = new WeakMap()
return o => {
if (! p.has(o)) p.set(o, {})
return p.get(o)
}
}
Yup, that’s all there is to it!
Create an accessor function and use it to associate private
data with objects. Only code that has access to the accessor
function can reach the private data.
import createAccessor from 'prv'
const prv = createAccessor()
class Point {
constructor(x, y) {
prv(this).x = x
prv(this).y = y
}
get x() {
return prv(this).x
}
get y() {
return prv(this).y
}
}
const point = new Point(0,0)
console.info(point.x) // 0
console.info(point.y) // 0
// attempting to set x
// ignored in 'sloppy' mode
// throws TypeError in strict mode
point.x = 10
Add an issue in the issue tracker
to let me know of any problems you find, or questions you may have.
Copyright 2018 by Stijn de Witt. Some rights reserved.
Licensed under the Creative Commons Attribution 4.0 International (CC-BY-4.0) Open Source license.