TypeScript学习笔记2

类的概念同java
注意: 派生类包含了一个构造函数,它就必须调用 super(),它会执行基类的构造函数

公共,私有与受保护的修饰符

同java

  • public (默认)
  • private 表示不能在声明它的类的外部访问
  • protected
    protected修饰符与 private修饰符的行为很相似,但有一点不同, protected成员在派生类中仍然可以访问

注意: 构造函数也可以被标记成 protected。 这意味着这个类不能在包含它的类外被实例化,但是能被继承

readonly修饰符
可以使用 readonly关键字将属性设置为只读的。 只读属性必须在声明时或构造函数里被初始化。

class Octopus {
    readonly name: string;
    readonly numberOfLegs: number = 8;
    constructor (theName: string) {
        this.name = theName;
    }
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; // 错误! name 是只读的.

参数属性:
代码功能同上,更加简洁

class Octopus {
    readonly numberOfLegs: number = 8;
    constructor(readonly name: string) {
    }
}

参数属性通过给构造函数参数前面添加一个访问限定符来声明。 使用 private限定一个参数属性会声明并初始化一个私有成员;对于 public和 protected来说也是一样。

存取器

通过getters/setters来截取对对象成员的访问
示例代码:

let passcode = "secret passcode";
class Employee {
    private _fullName: string;
    get fullName(): string {
        return this._fullName;
    }
    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    alert(employee.fullName);
}

注意: 只带有get不带有 set的存取器自动被推断为 readonly

静态属性static

存在于类的本身上,而不是实例上

抽象类abstract

抽象类做为其它派生类的基类使用。 它们一般不会直接被实例化。 不同于接口,抽象类可以包含成员的实现细节。 abstract关键字是用于定义抽象类和在抽象类内部定义抽象方法。

猜你喜欢

转载自blog.csdn.net/weixin_40693643/article/details/107447788