access-modifiers
日本語で読みたい方はこちら => README_JP
Introduction
easy use private/protected field for ES2015 class syntax
We should have complicated implementations to achieve private/protected access modifiers for ES2015 because of it has no such features for class syntax.
This module reduces the complication of the implementation for access modifiers.
npm install access-modifiers
You can add --save
or --save-dev
option for your project needs.
⚠️Requirements
The module requires ES2015 Proxy.
You should use a polyfill like tvcutsem/harmony-reflect if your expecting environment is not support the native Proxy.
The module also requires Symbol implementation.
You can use a polyfill like medikoo/es6-symbol.
In addition, the module is well suited to class syntax. To use the class syntax, you can use Babel.
Usage (Node.js)
Animal.js
; // the `create` method returns the objects for private and protected modifiersconst _p = AccessModifiers; { this_age = age; // access to a private field thispname = "Animal"; // access to a protected field } { return this_age; } { return thispname; } // restores the field information in a public method { return `Hello, my name is (age: ).`; } // finally, registers the objects for private and protected modifiers used on the Animal classAccessModifiers; ;
Gorilla.js
;; // you should give a base class to the `create` method for inheritanceconst _p = AccessModifiers; { superage; this_like = "Banana"; // access to a private field thispname = "Gorilla"; // access to a protected field (overrides the Animal's field) } { return this_like; } // overrides a public method (rewrite the protected `name` field used in the `super.introduce` method) { return ` I like a .`; } // finally, registers the objects for private and protected modifiers used on the Gorilla classAccessModifiers; ;
index.js
; // you do not have to this line if the native Proxy is supported;; const animal = 5;console; // "Hello, my name is Animal(age: 5)."animalage = 10; // cannot set the value because the `age` is getter propertyconsole; // 5 const gorilla = 8;console; // "Hello, my name is Gorilla(age: 8). I like a Banana." // you can forcefully get the field values for Reflectionconsole; // [symbol(name), symbol(age), symbol(like)]
Usage (Browsers supporting Proxy)
<!-- ensure to load browser.min.js --> <!-- ... -->
Usage (Browsers not supporting Proxy)
You had better not to put a dummy Proxy
<!-- ... -->