https://github.com/parro-it/private-class
Protect private properties of classes
https://github.com/parro-it/private-class
Last synced: 11 months ago
JSON representation
Protect private properties of classes
- Host: GitHub
- URL: https://github.com/parro-it/private-class
- Owner: parro-it
- License: mit
- Created: 2016-10-14T09:10:51.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2016-10-15T07:59:59.000Z (over 9 years ago)
- Last Synced: 2024-10-11T18:09:29.299Z (over 1 year ago)
- Language: JavaScript
- Homepage:
- Size: 50.8 KB
- Stars: 8
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
- License: license
Awesome Lists containing this project
README
# private-class
> A module to protect private properties of classes
This module allow to protect private properties of classes.
It works by creating a new prototype that wraps each methods of the original one.
On creation of a new instance of the wrapped prototype, a new instance of the original class is created and saved in a WeakMap.
Wrapped methods retrieve the original class instance from there and forward the call to its method.
## Usage
```js
const priv = require('private-class');
const Person = priv(class Person {
constructor(name, age) {
this._name = name;
this._age = age;
}
get age() {
return this._age;
}
set age(value) {
this._age = value;
}
name() {
return this._name;
}
});
const p = new Person('Andrea', 40);
// public function are visible
console.log(typeof p.name);
// <-- function
// public getter & setter are visible
p.age = 41;
console.log(p.age);
// <-- 41
// public function can read private fields
console.log(p.name());
// <-- Andrea
// extern code can not read private fields
console.log(p._name);
// <-- undefined
console.log(p._age);
// <-- undefined
```
[](http://travis-ci.org/parro-it/private-class)
[](https://codeclimate.com/github/parro-it/private-class)
[](https://coveralls.io/github/parro-it/private-class?branch=master)
[](https://npmjs.org/package/private-class)
## API
```js
const privateClass = (Class: function): function
```
Given a class, return a new class that doesn't allow to access private properties.
## Install
With [npm](https://npmjs.org/) installed, run
```
$ npm install private-class
```
## See Also
- [`noffle/common-readme`](https://github.com/noffle/common-readme)
## License
MIT