Original artial --> linkjavascript
How descorator looks like:html
@mydecorator
function myFun(){
...
}
Descorator in action:java
We have a class, which have an method call meow():git
class Cat { meow(){ console.log(`Meow!!`); } }
When Javascritp Engine read it, it looks like:github
Object.defineProperty(Cat.prototype, 'meow', { value: specifiedFunction, enumerable: false, configurable: true, writable: true, })
Imagine we want to mark a property or method name as not being writable. A decorator precedes the syntax that defines a property. We could thus define a`@readonly` decorator for it as follows:express
function readonly(target, key, descriptor){ descriptor.writable = false; return descriptor; }
and add it to our meow property as follows:npm
class Cat { @readonly meow() { return `say meow!` } }
Now, before installing the descriptor onto `Cat.prototype`, the engine first invokes the decorator:babel
Then if you have mark 'writable' to 'false' by adding @readonly descortaor, if we trying to overwrite the 'meow' method, it will report error.ecmascript
Check out libaray, it has many pre-defined descorators: npm, Githubpost
Decorate a class:
function superhero(isSuperhero ){ return function(target){ return class{ isSuperhero = isSuperhero } } } @superhero(true) class MySuperHero{ isSuperhero = null; constructor(){} } const hero = new MySuperHero(); console.log(hero.isSuperhero); //true
Continue reading: