@anywhichway/privatize

0.0.2-b • Public • Published

privatize

Inheritable or instance level closure based fully private properties for JavaScript. Add one line of code to existing classes.

Installation

npm install @anywhichway/privatize

Usage

Just call privatize with the target object and the private data at the beginning of your constructor, right after super if super is needed. If you want inheritable methods to use the data, then add a class reference as a third argument at the level you wish to inherit from.

const privatize = require("@anywhichway/privatize");
// or load using script tag in browser

class Named {
	constructor(name) {
		privatize(this,{name},Named);
	}
	getName() {
		return this.name;
	}
}

class AbstractPerson extends Named {
	constructor(name) {
		super(name);
	}
}

class Person extends AbstractPerson {
	constructor(name) {
		super(name);
	}
	setName(name) {
		this.name = name.toUpperCase();
	}
}

const person1 = new Person("joe"),
	person2 = new Person("jane");

console.log(person1); // object but can't see name
console.log(person1.name); // undefined
console.log(person1.getName()); // joe
console.log(person2); // object but can't see name
console.log(person2.name); // undefined
console.log(person2.getName()); // jane
console.log(person1.setName(person1.getName())) // undefined
console.log(person1.getName()); // JOE
console.log(person2.getName()); // jane

Updates (reverse chronological order)

2019-02-09 v0.0.2b - Fixed instanceof checks

2019-02-09 v0.0.1b - Initial public release

License

MIT

Package Sidebar

Install

npm i @anywhichway/privatize

Weekly Downloads

1

Version

0.0.2-b

License

MIT

Unpacked Size

9.7 kB

Total Files

9

Last publish

Collaborators

  • anywhichway