Karl

诸葛亮从来不问刘备,为什么我们的箭那么少?关羽从来不问刘备,为什么我们的兵那么少?张飞从来不问刘备,兵临城下应该怎么办?如若万事齐备,你的价值何在?

博客园 首页 新随笔 联系 订阅 管理

Original artial --> link

 

How descorator looks like:

@mydecorator
function myFun(){
  ...
}

 

Descorator in action:

We have a class, which have an method call meow():

class Cat {
  meow(){
     console.log(`Meow!!`);
  }   
}

When Javascritp Engine read it, it looks like:

复制代码
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:

function readonly(target, key, descriptor){
    descriptor.writable = false;
    return descriptor;
}

and add it to our meow property as follows:

复制代码
class Cat {
    @readonly
    meow() {
        return `say meow!`
    }
}
复制代码

Now, before installing the descriptor onto `Cat.prototype`, the engine first invokes the decorator:

 

Then if you have mark 'writable' to 'false' by adding  @readonly descortaor,  if we trying to overwrite the 'meow' method, it will report error.

 

Check out libaray, it has many pre-defined descorators: npmGithub

 

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:

posted on 2020-09-25 15:50  半雪  阅读(128)  评论(0编辑  收藏  举报