typescript裝飾器

裝飾器是一種特殊類型的聲明,它能夠被附加到類聲明,方法, 訪問符,屬性或參數(shù)上。

類裝飾器

const classDec: ClassDecorator = (target: Function) => {
  target.prototype.myClassName = "類裝飾器";
  target.prototype.getClassName = <T>(params: T, param2: number) => {
    console.log(`我是方法里的${params}${param2}`);
    return params;
  };
};

@classDec
class MyClassD {}

let myClassD = new MyClassD();

// console.log(myClassD)
// console.log((myClassD as any).myClassName)
// console.log((myClassD as any).getClassName(123,'zhang'));

工廠裝飾器
其實也就是一個高階函數(shù) 外層的函數(shù)接受值 里層的函數(shù)最終接受類的構(gòu)造函數(shù)
?相同函數(shù)名稱只執(zhí)行先注冊的

const facDec = (params:string): ClassDecorator => {
  return (fun:Function)=>{
    fun.prototype.say = ()=>{
        console.log(`i say${params}`)
    }
  };
};

@facDec('世界和平')
class MyFacDec{
    say(){

    }
}

let myFacDec = new MyFacDec()
myFacDec.say()

裝飾器組合

@watcher2('myYname')
@watcher
class AA {
    constructor() {
 
    }
}
 
const aaTest = new AA();
console.log((aaTest as any).getParams('123wode'));
console.log((aaTest as any).getOptions());

方法裝飾器

//普通方法裝飾器
const methodDec: MethodDecorator = (
  target,
  propertyKey,
  descriptor: PropertyDescriptor
) => {
  const method = descriptor.value;
  descriptor.value = () => {
    console.log(`重寫方法`);
  };
};
//靜態(tài)方法裝飾器
const staticMethodDec: MethodDecorator = (
  target,
  propertyKey,
  descriptor: PropertyDescriptor
) => {
  const method = descriptor.value;
  descriptor.value = () => {
    console.log(`重寫靜態(tài)方法`);
  };
};

class MyMethod {
  @methodDec
  public showMethod() {
    console.log(`來吧展示普通方法`);
  }
  @staticMethodDec
  public static showStaticMethod() {
    console.log(`來吧展示靜態(tài)方法`);
  }
}

let myMethodD = new MyMethod();

// console.log(myMethodD)
// myMethodD.showMethod()

// MyMethod.showStaticMethod()

屬性裝飾器

const proDec: PropertyDecorator = (target, propertyKey) => {
  let myvalue: string;
  Object.defineProperty(target, propertyKey, {
    get() {
      return myvalue.toLocaleLowerCase();
    },
    set(v) {
      myvalue = v;
    },
  });
};
class Student {
  @proDec
  public name: string;
  public age: number;
  constructor(n: string, a: number) {
    this.name = n;
    this.age = a;
  }
  say() {
    console.log(`${this.name}age is ${this.age}`);
  }
}

let xiaogang = new Student("ZhAngsan", 19);
// xiaogang.say()
// console.log(xiaogang.name)

元數(shù)據(jù)

Reflect.defineMetadata("myname", "12", myFacDec,'title');
console.log(Reflect.getMetadata("myname",myFacDec,'title'))
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容