Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/trakkasure/babel-plugin-transform-private-properties
Provides private properties by using WeakMap
https://github.com/trakkasure/babel-plugin-transform-private-properties
Last synced: 3 months ago
JSON representation
Provides private properties by using WeakMap
- Host: GitHub
- URL: https://github.com/trakkasure/babel-plugin-transform-private-properties
- Owner: Trakkasure
- Created: 2016-07-18T01:22:28.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2016-08-21T18:47:44.000Z (over 8 years ago)
- Last Synced: 2024-10-11T23:04:14.233Z (3 months ago)
- Language: JavaScript
- Size: 19.5 KB
- Stars: 4
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# babel-plugin-transform-private-properties
Compile private variables into classes utilizing weak maps.
## Installation
```sh
$ npm install babel-plugin-transform-private-properties
```## Usage
### Via `.babelrc` (Recommended)
**.babelrc**
```json
{
"plugins": ["babel-plugin-transform-private-properties"]
}
```### Via CLI
```sh
$ babel --plugins babel-plugin-transform-private-properties script.js
```### Via Node API
```javascript
require("babel-core").transform("code", {
plugins: ["babel-plugin-transform-private-properties"]
});
```## Implementation
```javascript
class TestClass {@Private
p=1; // Decalare private var. Very important, @Private is on it's own line, and is capitalized.@Private
s;// Declare non-private class property.
j=2;
constructor() {
this.p = 2; // Setting private.var self = this // Yes, we follow copying this scope.
, other="gone";self.p = this.p.g; // Setting private (p) self is assigned to "this" so assign p to value of p.g
this.func1("constructor",this.p); // Call func1 (which is private) with options. Can't call fun1 outside of this class.
var me;
me = self; // Yes, we follow copying this scope too.me.s = 5;
me.p = 7;
me.j = 8;
self = me;
self.p = me.p;
}
// You can create public functions with same name as private variable as a way to access the private in a controlled way.
p() {
return this.p;
}// Getters can be the same as a private variable to gate-keep access.
get s { // this probably shouldn't be allowed to work.
return this.s;
}@Private
func1(fromWhere) {
console.log("This is the first function called from ",fromWhere);
}
}
```This results in the usage such as:
```javascript
var t = new TestClass();
t.func1("Outside"); // t.func1 is not a function
t.s = "hi" // TypeError: Cannot set property s of # which has only a getter
console.log(t.s); //outputs "5"
console.log(t.p()) // outputs "7"
```