Skip to content

Instantly share code, notes, and snippets.

@eavichay
Created October 17, 2017 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eavichay/cafb6cbf53129a9c46b36dfcda018bef to your computer and use it in GitHub Desktop.
Save eavichay/cafb6cbf53129a9c46b36dfcda018bef to your computer and use it in GitHub Desktop.
decorators example
// code
const foo = function(target) {
target.prototype.foo = function() {
console.log("foo");
}
}
const bar = function(myText) {
return function(target) {
target.prototype.bar = function() {
console.log(myText);
}
}
}
const readonly = (target, key, descriptor) => {
descriptor.writable = false;
}
const deprecated = (target, key, descriptor) => {
const old = descriptor.value;
descriptor.value = () => {
console.log('deprecated');
old();
}
}
// Object.defineProperty(target, key, descriptor)
@foo
@bar('BAR')
class MyClass {
constructor() {
this.foo();
this.bar();
this.myMethod();
this.myProp = '456';
}
@readonly
myProp = '123';
@deprecated
myMethod() {
console.log('this should not happen');
}
}
new MyClass()
// .babelrc
{
"presets": ["env"],
"plugins": ["transform-decorators-legacy", "transform-class-properties"]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment