TypeScript-类的修饰器

70 阅读1分钟

public、private和protected

class Person {
    name="张三"
    age=18
    protected say() {
        console.log(`我的名字是${this.name},年龄${this.age}`)
    }
    test() {
        this.say() // 内部可以访问
    }
    private test2() { // private不可以继承父类
        console.log(123)
    }
    static test3() {
        console.log('test3') // 加上static,外部可以直接调用
    }
}

Person.test3(); // 加上static,外部可以直接调用

var p = new Person();
p.say(); // private不能被外部访问,故报错

class Child extends Person {
    callParent() {
        super.say() // protected可以继承父类
        super.test2() // private不可以继承父类
    }
}