[ES7] Exploring ES2016 Decorators

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[ES7] Exploring ES2016 Decorators相关的知识,希望对你有一定的参考价值。

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: npm, Github

 

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:

以上是关于[ES7] Exploring ES2016 Decorators的主要内容,如果未能解决你的问题,请参考以下文章

如何在 nodejs 中使用 ES7?

ECMA Script 2016 (ES7)新内容

ECMA Script 2016 (ES7)新内容

ECMA Script 2016 (ES7)新内容

ES7(2016)幂运算符**

ES7新特性