文档http://es6.ruanyifeng.com/#docs/decorator
ts文档 https://www.tslang.cn/docs/handbook/decorators.html#class-decorators
当多个装饰器应用于一个声明上,从上至下调用,从下而上执行
interface InfoOpt {
username: string;
age: number;
email: string;
}
function Info(opt: InfoOpt) {
return function (target) {
target.username = opt.username;
target.age = opt.age;
target.email = opt.email;
}
}
@Info({
username: 'ajanuw',
age: 14,
email: '123@sina.com'
})
class AJanuw {
constructor() { }
}
console.log(
AJanuw.username,
AJanuw.age,
AJanuw.email,
);
es 的装饰器
let l = console.log
function klass(value) {
return target => {
// l(value) // api
// l(target) // 对象
}
}
function prop(value) {
return function (target, key, des) { // target 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象
// l(value) // username
// l(target, key, des) // 对象,属性名,属性描述符
}
}
function func(value) {
return function (target, key, des) { // // target 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象
// l(value) // function
// l(key) // 函数名 show
// l(des.value) // show函数, 可以改写
// des.value = function(){
// l('hello')
// }
}
}
function Body(target) {
// l( target ) // undefined
}
@klass('api')
class Ajanuw {
@prop('username') name = 'ajanuw'
@func('function')
show(@Body body) {
l(body)
}
}
new Ajanuw().show()