decorator(装饰器)

配置demo环境

1
2
3
4
5
6
7
8
9
10
{
"scripts": {
"babel-version": "babel --version"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-plugin-transform-decorators-legacy": "^1.3.5",
"babel-register": "^6.26.0"
}
}

demo1

  • 创建APP.js
1
2
3
4
5
6
7
8
9
// 装饰器
@test
class hello {}
// 利用这个东西可以为类hello添加新的属性或者改变里面的属性
function test(target) {
// target为楼上的hello类
target.isT = true;
}
console.log(hello.isT);
  • 创建complie.js

    因为demo是利用node直接运行,因此利用babel-register来使node环境能跑

    1
    2
    3
    4
    require('babel-register')({
    plugins: ['transform-decorators-legacy']
    });
    require("./app.js")

理解decorator

1
2
3
4
5
6
7

@decorator
class hello {}

//楼上的写法即是楼下这种,装饰器修饰了一下再继续返回给了类hello
class hello {}
hello = decorator(hello) || hello;

demo2[装饰器传参]

依旧是写在app.js,然后执行node complie.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 为value传入true
@value(true)
class demoOne{}
// 在这一种有参数的情况下,我们使用了两层嵌套的方式,先传入了装饰器带的值,然后再return一个函数来用于处理我们需要装饰的类demoOne,target依旧是我们定义的类
function value(val) {
return function(target) {
target.isTable = val;
}
}
console.log(demoOne.isTable)// true
// 为value传入false
@value(false)
class demoTwo{}
function value(val) {
return function(target) {
target.isTable = val;
}
}
console.log(demoTwo.isTable)// false

demo3[装饰器添加实例属性]

1
2
3
4
5
6
7
8
9
10
@objectTest
class helloTest {}
// 利用这个东西可以为类hello添加新的属性或者改变里面的属性
function objectTest(target) {
// target为楼上的hello类
target.prototype.isTable = true;
}
let newhelloTest = new helloTest();
console.log(helloTest.isTable,newhelloTest.isTable);
// undefine,true

以上是装饰器对类的处理,装饰器还有修饰类的属性等功能。。。