码迷,mamicode.com
首页 > 其他好文 > 详细

[ES7] Exploring ES2016 Decorators

时间:2016-06-13 06:35:16      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/5579327.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!