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
1 2 3 4 5 6 7 8 9
| @test class hello {}
function test(target) { 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 {}
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) class demoOne{}
function value(val) { return function(target) { target.isTable = val; } } console.log(demoOne.isTable)
@value(false) class demoTwo{} function value(val) { return function(target) { target.isTable = val; } } console.log(demoTwo.isTable)
|
demo3[装饰器添加实例属性]
1 2 3 4 5 6 7 8 9 10
| @objectTest class helloTest {}
function objectTest(target) { target.prototype.isTable = true; } let newhelloTest = new helloTest(); console.log(helloTest.isTable,newhelloTest.isTable);
|
以上是装饰器对类的处理,装饰器还有修饰类的属性等功能。。。