encap
v1.1.0
Published
A micro NPM module that aids in encapsulation of object properties.
Downloads
3
Maintainers
Readme
encap
aids in object property encapsulation
Installation | Usage | Example | License
Installation
With npm:
npm install encap --save
Note: You need an engine that supports ES6 (e.g. Babel or Node 4.0+).
Usage
encap(obj)(props[, options])
Default behavior is the creation of getters and setters for private, encapsulated variables (defined by props
)
props
must be an object where the keys are the property names and the values are the default values.
options
can have the following:
readonly
: Iftrue
, does not create a setter, and sets property as notwritable
. (Default:false
)enumerable
: Iffalse
, does not allow enumeration (i.e.console.log(obj)
will not log the property) (Default:true
)set
: Optional function with parameters (oldVal
,newVal
). The property will be set to the return value of this function.get
: Optional function with parameter (val
). Runs onget
. Theget
function will return the value of this function.
Example
'use strict'
import encap from 'encap'
class Person {
constructor (name, age, gender) {
// Store encap function
const store = encap(this)
// Add private attributes
store({ name })
store({ age, gender }, { readonly: true, enumerable: false })
}
}
// Add a static class attribute
encap(Person)({ num: 1 })
After instantiating the class:
const p = new Person('Bob', 18, 'M')
// Trying to modify a readonly prop will throw.
p.gender = 'B'
// TypeError: Cannot assign to read only property 'label' of #<Point2d>
console.log(p.age) // 18
console.log(p.gender) // 'M'
console.log(p) // Person { name: 'Bob' }
console.log(Person.num) // 1