TypeScript 类与装饰器模式

  1. public/protected/private 关键字与继承
// 当ts文件内含有import或export关键字时 会默认认为该文件是个模块
// 此时可以重复声明其他文件声明过的变量
export {}
// 类
class Father {
  static fatherMoney: number = 100;
  public name: string; // 公共的  父类 父类实例 子类 子类实例皆可访问
  protected age: number; // 被保护的 只有父类和子类可以访问
  private book: string; // 私有的 只能在父类中访问
  constructor(name: string, age: number, book: string) {
    this.name = name;
    this.age = age;
    this.book = book;
  }
}
// 子类继承父类时会继承所有可被继承的属性/方法和静态属性/方法
class Son extends Father {
  isSon: boolean;
  constructor(name: string, age: number, isSon: boolean, book: string) {
    super(name, age, book); 
    this.isSon = isSon;
  }
  sendBook() {
    // console.log(this.book);
  }
}

const fa = new Father('zs', 30, '水浒转');
// console.log(fa.book);
// console.log(fa.age);
const son = new Son('ls', 18, true, '三国演义');
// console.log(son.book);
// console.log(son.age);
  1. 装饰器模式
export {}
// 命名空间可以理解为一个闭包函数 这样该函数作用域中的变量和其他作用域的互不影响
namespace a { // 命名空间
  
  // 装饰器函数 接收的变量为构造函数本身
  function addNameEat(c: Function) {
    c.prototype.name = 'zs';
    c.prototype.eat = function () {
      console.log('eat');
    }
  }
  // @符定义装饰器 如果要在ts中使用装饰器模式 需要在tsconfig.js中
  // 启用对装饰器的支持  "experimentalDecorators": true,
  @addNameEat
  class Person {
    name: string;
    eat: Function;
    constructor(){}
  }
  const p: Person = new Person();
  console.log(p.name); // zs
  p.eat();	//eat
}

namespace b {
  // 工厂装饰器
  // 利用闭包延申形参的作用域  来给类动态添加属性
  // 注意: 装饰器可以替代继承
  function addNameEatFactory(name: string, eat: Function) {
    return  function addNameEat(c: Function) {
      c.prototype.name = name;
      c.prototype.eat = eat;
    }
  }

  @addNameEatFactory('ls', function(){console.log('eat more');})
  class Person {
    name: string;
    eat: Function;
    constructor(){}
  }
  const p: Person = new Person();
  console.log(p.name); // ls
  p.eat(); // eat more
}