ts中的类和es6中大体相同,

    1. class Parent {
    2. private _foo = "foo"; // 私有属性,不能在类的外部访问
    3. private foobar = "foobar"; // 公开属性,能在类的外部访问
    4. protected protectedBar = "protectedBar"; // 保护属性,可以在子类中访问
    5. // 参数属性:构造函数参数加修饰符,能够定义为成员属性
    6. constructor(public tua = "tua") {}
    7. // 方法也有修饰符
    8. // 私有方法,不能在类的外部访问
    9. private privateMethod() {
    10. console.log(this);
    11. }
    12. // 公开方法,不能在类的外部访问
    13. public publicMethod() {
    14. console.log(this);
    15. }
    16. // 保护方法,可以在子类中访问
    17. protected protectedSay() {
    18. console.log("protectedSay");
    19. }
    20. // 存取器:属性方式访问,可添加额外逻辑,控制读写性
    21. get foo() {
    22. return this._foo;
    23. }
    24. set foo(val) {
    25. this._foo = val;
    26. }
    27. // 静态方法
    28. static isParent(a: any) {
    29. return a instanceof Parent;
    30. }
    31. }

    继承,

    1. class ChineseParent extends Parent {
    2. constructor(public from = "gd") {
    3. super("tuatuatua"); // 调用父类的 constructor
    4. }
    5. getProtected() {
    6. // 获取父类的保护属性
    7. console.log(this.protectedBar);
    8. // 获取父类的保护方法
    9. console.log(this.protectedSay());
    10. }
    11. }