1.1.0 • Published 7 years ago

encap v1.1.0

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

encap

aids in object property encapsulation

NPM version Build Status js-standard-style

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: If true, does not create a setter, and sets property as not writable. (Default: false)
  • enumerable: If false, 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 on get. The get 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

License

MIT