class类

127 阅读1分钟

1)class的基本用法 继承 和 类型约束 implement

2)class的修饰符 readonly private protected public

readonly只读,不可修改

private 私有成员,只允许本类调用,子类和实例化对象均不可用

protected 保护成员,允许父类和子类调用,实例化对象不可用

public 公共成员,允许父类、子类、实例化对象使用

3)super原理

4)静态方法

静态方法里的this只能调用其他静态方法或静态属性

5)get set


// class的类型约束
interface InterfaceA {
    _choice: string,
    init: () => void,
}

class Base {
    _name: string  // 属性定义的位置
    constructor(name: string) {
        this._name = name;
        this.private_func()
        this.protected_func()
        this.public_func()
    }

    private private_func(): void {
        console.log('private私有方法,仅Base类内部可以用')
    }

    protected protected_func(): void {
        console.log('protected方法,仅Base类及子类内部可调用')
    }

    public public_func(): void {
        console.log('public默认修饰,哪里都能用,实例化对象也可以')
    }
}

class Test extends Base implements InterfaceA {
    _choice: string       // 实例化对象可引用
    static _k1: string   // 类方法可引用
    readonly _k2: string  // 实例化对象可引用,但属性不能被修改

    constructor(name: string, choice: string, k2) {
        super(name);
        this._choice = choice;
        this._k2 = k2
        this.init();
    }

    init(): void {
        console.log('初始化方法,自动运行')
        console.log(this._name)
        console.log(this._choice)
        this.protected_func()
        this.public_func()
    }

    static static_func1(): void {
        this._k1 = 'static_k1';
        console.log('静态方法,通过Test.method1()直接调用');
        console.log(this._k1);
        console.log('静态方法,只能访问静态属性和其他静态方法');
        this.static_func2();
    }

    static static_func2(): void {
        console.log('我是静态方法static_func2');
    }
}

// let t1 = new Test('menffy', 'success','readonly_k2')
// t1.public_func()
// t1._k2 = 12 // Attempt to assign to const or readonly variable
// Test.static_func1()
// console.log(Test._k1)

6)基类、抽象类

  • abstract 所定义的抽象类
  • abstract 所定义的方法是不能实现的,只能描述。派生类继承基类后必须实现该方法。
  • 抽象类无法被实例化
abstract class Base {
    _name: string

    protected constructor(name?: string) {
        this._name = name;
    }

    abstract init(name: string): void

    getName() {
        return this._name;
    }
}

class Test extends Base {
    constructor() {
        super();
    }

    init(name: string) {
        this._name = name;
    }
}

const obj = new Test();
obj.init('menffyzheng')
console.log(obj.getName())