Skip to content

Instantly share code, notes, and snippets.

@aloerina01
Last active March 14, 2017 09:07
Show Gist options
  • Save aloerina01/1fa30b0d81384681a4480d80e69893fe to your computer and use it in GitHub Desktop.
Save aloerina01/1fa30b0d81384681a4480d80e69893fe to your computer and use it in GitHub Desktop.
ES6 Proxy - 実用例ModuleBuilder
export default class {
constructor() {
this._moduleClass = {};
this._handler = {};
}
class(moduleClass) {
this._moduleClass = moduleClass;
return this;
}
handler(handler) {
this._handler = Object.assign(this._handler, handler);
return this;
}
build() {
return new Proxy(this._moduleClass, this._handler);
}
}
export const Handlers = {
PrivateValiables: {
set(target, prop, value, receiver) {
if (prop.indexOf('_') === 0) {
throw new TypeError(`${prop} is private valiable`);
}
return Reflect.set(target, prop, value, receiver);
},
get(target, prop, receiver) {
if (prop.indexOf('_') === 0) {
throw new TypeError(`${prop} is private valiable`);
}
return Reflect.get(target, prop, receiver);
},
deleteProperty(obj, prop) {
if (prop.indexOf('_') === 0) {
throw new TypeError(`${prop} is private valiable`);
}
return Reflect.deleteProperty(obj, prop);
},
construct(target, args) {
return new Proxy(Reflect.construct(target, args), Handlers.PrivateValiables);
}
},
Immutable: {
set(target, prop, value, receiver) {
throw new TypeError(`This object is immutable.`);
},
get(target, prop, receiver) {
console.warn('This object is immutable, so you should call an exclusive getter function.')
return Reflect.get(target, prop, receiver);
},
deleteProperty(obj, prop) {
throw new TypeError(`This object is immutable.`);
},
construct(target, args) {
return new Proxy(Reflect.construct(target, args), Handlers.Immutable);
}
},
Singleton: {
set(target, prop, value, receiver) {
if (prop.indexOf('_') === 0) {
throw new TypeError(`${prop} is private valiable`);
}
return Reflect.set(target, prop, value, receiver);
},
get(target, prop, receiver) {
if (prop.indexOf('_') === 0) {
throw new TypeError(`${prop} is private valiable`);
}
return Reflect.get(target, prop, receiver);
},
deleteProperty(obj, prop) {
if (prop.indexOf('_') === 0) {
throw new TypeError(`${prop} is private valiable`);
}
return Reflect.deleteProperty(obj, prop);
},
construct(target, args) {
throw new TypeError('This class is a singleton instance, so you should call getInstance() function.');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment