我是靠谱客的博主 明理蚂蚁,这篇文章主要介绍016-Decorator(修饰器,是一个函数,用来修改类的行为),现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/** * Decorator(修饰器,是一个函数,用来修改类的行为) * 扩展类的功能 * * 第三方库修饰器的js库:core-decorators; npm install core-decorators * */ { //基本用法 1 /** * * @param target 修改的类的本身 * @param name 修改类属性的名称 * @param descriptor 该属性的描述对象 * @returns {*} */ let readonly=function(target,name,descriptor){ descriptor.writable=false; //限制不可写 return descriptor }; class Test{ @readonly //调用修饰器 time(){ return '2017-03-11' } } let test=new Test(); // 修改time()函数会报错 // test.time=function(){ // console.log('reset time'); // }; console.log(test.time()); } { //基本用法 2 let typename=function(target,name,descriptor){ target.myname='hello'; } @typename class Test{ } console.log('类修饰符',Test.myname); //hello // 第三方库修饰器的js库:core-decorators; npm install core-decorators } /** * 前端日志系统 ******************************************** */ { let log=(type)=>{ return function(target,name,descriptor){ let src_method=descriptor.value; descriptor.value=(...arg)=>{ src_method.apply(target,arg); console.info(`log ${type}`); } } } class AD{ @log('show') show(){ console.info('ad is show') } @log('click') click(){ console.info('ad is click'); } } let ad=new AD(); ad.show(); ad.click(); }

最后

以上就是明理蚂蚁最近收集整理的关于016-Decorator(修饰器,是一个函数,用来修改类的行为)的全部内容,更多相关016-Decorator(修饰器,是一个函数,用来修改类内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(61)

评论列表共有 0 条评论

立即
投稿
返回
顶部