TypeScript的基本语法(二)

TypeScript的基本语法(一)
修饰器
主要作用是对类及其成员的再处理!Angular里经常用到。
类修饰器

//对其修饰的类进行再加工
function classD(t){
  let k = new t();
  console.log(k.age);//17
  t.prototype.name = "scy";
}
@classD
class User {
  public age:string = "17";
}

let u:any = new User();
console.log(u.name);//scy
export {};

方法修饰器

//三个参数:类的原型  方法名  对象属性的特性描述
function met(prototype, method:string, des:PropertyDescriptor){
  console.log(arguments);
  /*
  { '0': User {},
    '1': 'test',
    '2':
     { value: [Function: test],
       writable: true,
       enumerable: false,
       configurable: true } }
  */
}
class User {
  @met
  test() {
    console.log("1111");
  }
}
// let u = new User();
// u.test = function() {
//   console.log("22222");
// }
// u.test();//22222
export {};

属性修饰器

//有两个prop 所以这里会进入两次
function prop(prototype, propName){
  console.log(arguments);
  if(!prototype.propList){
    prototype.propList=[];
  }
  prototype.propList.push(propName);//将所有属性修饰器修饰的属性 加到原型下的数组里
  //console.log(prototype.propList);
}

class User{
  @prop
  private name:string;
  @prop
  age:number;

  print(){
    let self:any = this;
    console.log(self.propList);
  }
}
let u = new User();
u.print();//[ 'name', 'age' ]
export {};

参数修饰器

function arg(prototype,methodName:string, index:number ){
  console.log(arguments);
  if(!prototype.methodList){
    prototype.methodList = [];
  }
    prototype.methodList.push(methodName);
}
class User{
  private name:string;
  age:number;

  test(@arg name:string,@arg age:number){
    let self = this;
  }
}
let u:any = new User();
console.log(u.__proto__)//User { methodList: [ 'test', 'test' ] }
export {};

猜你喜欢

转载自blog.csdn.net/chaoyangsun/article/details/80296259