方法装饰器
- 普通方法,target 对应的是类的 prototype;
- 静态方法,target 对应的是类的构造函数
- key 对应的是方法名; descriptor 可以操控属性描述符( prototype descriptor )对象
- 方法装饰器也是等类创建好之后就会立即执行 ```typescript function getNameDecorator(target: any,key: string,descriptor: PropertyDescriptor) { // 方法将不能重写 descriptor.writable = false; // 返回值变为 descriptor descriptor.value = () => { return “descriptor”; }; console.log(target, key); } class Test { name: string; constructor(name: string) { this.name = name; } @getNameDecorator getName() { return this.name; } }
let test = new Test(“zws”); console.log(test.getName()); // descriptor
<a name="tNKH3"></a>## 访问器装饰器- 访问器装饰器跟方法装饰器接收的参数一样```typescriptfunction visitDecorator(target: any,key: string,descriptor: PropertyDescriptor) {console.log(key);}class Test {private _name: string;constructor(name: string) {this._name = name;}get name() {return this._name;}@visitDecoratorset name(name: string) {this._name = name;}}let test = new Test("zws");test.name = "zws";console.log(test.name);
属性装饰器
- 接收两个参数:target(test 对应的prototype),key(属性名)
- 修改的是并不是实例上的 name,而是原型上的 name ```typescript function nameDecorator(target: any, key: string): any { target[key] = “zbl”; }
class Test { @nameDecorator name = “zws”; }
let test = new Test(); console.log(test.name, (test as any).proto.name);
<a name="9uIhd"></a>## 参数装饰器- 接收三个参数:原型、方法名、参数所在位置```typescriptfunction paramDecorator(target: any, key: string, parameIndex: number): any {console.log(target, key, parameIndex);}class Test {getInfo(@paramDecorator name: string, age: number) {console.log(`姓名:${name};年龄:${age}`);}}let test = new Test();test.getInfo("zws", 13);
