es6(16)--Decorator

 1 //Decorator:修饰器,是一个函数用来修改类的行为
 2 {
 3     //只读
 4     let readonly=function(target,name,descriptor){
 5         descriptor.writable=false;
 6         return descriptor;
 7     };
 8     class Test{
 9         @readonly
10         time(){
11             return '2017-03-11'
12         }
13     }
14     let test=new Test();
15     // test.time=function(){
16     //     console.log('reset time');
17     // }
18     console.log(test.time())
19 }
20 {
21     let typename=function(target,name,descriptor){
22         target.myname="hello";
23     }
24     @typename
25     class Test{
26 
27     }
28     console.log(Test.myname)
29 }
30 //常用的修饰器的js库,core-decorators;cnpm install core-decorators --save-dev
31 {
32     let log=(type)=>{
33         return function(target,name,descriptor){
34             let src_method=descriptor.value;
35             descriptor.value=(...arg)=>{
36                 src_method.apply(target,arg);
37                 console.info(`log ${type}`);
38             }
39         }
40     }
41     class AD{
42         @log('show')
43         show(){
44             console.info('ad is show')
45         }
46         @log('click')
47         click(){
48             console.info('ad is click')
49         }
50     }
51     let ad=new AD();
52     ad.show();
53     ad.click();
54 }
原文地址:https://www.cnblogs.com/chenlw/p/9227935.html