Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Class definition
- class AppDescription {
- constructor(obj = {}) {
- if ((Object.keys(obj).length)) {
- this.name = obj.name !== undefined ? obj.name : 'Default app name';
- this.version = obj.version !== undefined ? obj.version : 'Default version';
- } else {
- console.warn('Please provide a valid configuration object...');
- }
- }
- }
- let conf = {
- name: 'Amazing app',
- version: '1.0.0'
- };
- // Creating an 'app' instance based on class 'AppDescription'
- let app = Reflect.construct(AppDescription, [conf]);
- // Defining a proxy handler for our app
- let appProxyHandler = {
- get: (target, name) => {
- if (Reflect.has(target, name)) {
- return Reflect.get(target, name);
- } else {
- console.warn(`Property "${name}" does not exist.`);
- }
- },
- set: (target, property, value) => {
- switch(Object.prototype.toString.call(value)) {
- case ('[object Array]'):
- if (value.length >=2) {
- Reflect.set(target, property, value);
- } else {
- console.warn(`Arrays min. length: 2`);
- }
- break;
- case ('[object Object]'):
- break;
- if (value.length >=3) {
- Reflect.set(target, property, value);
- } else {
- console.warn(`Objects min. length: 3`);
- }
- case ('[object String]'):
- if (value.length >= 4) {
- Reflect.set(target, property, value);
- } else {
- console.warn(`Property "${property}" should be at least 4 characters long.`)
- }
- break;
- default:
- console.warn('Please provide a correct value type.');
- }
- },
- defineProperty: (target, property, value) => {
- //Pro tip: define some checks in this trap as well!
- Reflect.set(target, property, value);
- }
- }
- // Creating our app proxy + using the proxy handler
- let appDescProxy = new Proxy(app, appProxyHandler);
- //Doing some tests:
- // Will fail
- Reflect.set(appDescProxy, 'name', 'Foo');
- Reflect.get(appDescProxy, 'authors');
- // Will work
- Reflect.set(appDescProxy, 'name', 'Super App');
- Reflect.get(appDescProxy, 'name');
- Reflect.defineProperty(appDescProxy, 'authors', {
- value: ['Erik J.', 'John Doe'],
- writable: true,
- configurable: true
- });
- Reflect.get(appDescProxy, 'authors');
Add Comment
Please, Sign In to add comment