ts中的类

147 阅读2分钟
// 4.类

// private public protected readonly 类中的描述符
// class Pointer {
//     // public x:number 
//     // public y:number  // 声明的变量会被增加到实例上
//     // 此函数中依然可用使用 剩余运算符 可选参数  默认参数

//     // 传入的实例直接就放在实例上,无需再次声明  
//     constructor(public x:number,public y:number){ // 在constructor中的操作都是初始化操作
//         // this.x = x;
//         // this.y = y;
//     }
// }
// let pointer = new Pointer(100,100)
// console.log(pointer.y,pointer.x)

// public 是属性修饰符  public 表示自己 和 子类 和子类之外都可以访问到
// protected 只有自己和 自己的后辈能访问
// private  就是只有自己能访问的属性
// 可以给构造函数添加修饰符,如果被标识成 protected不能在类外面被new 了, 如果被标识成private不能被子类继承了,同时也不能被new
// readonly,仅读 (const),如果在初始化完毕后不能在修改了,如果是对象可以更改属性

class Animal {
    public readonly n: number = 1 // 如果n是对象,可以在初始化之外修改属性值
    // public constructor(public name: string, public age: number) {
    // private constructor(public name: string, public age: number) {
    protected constructor(public name: string, public age: number) {
        this.n = 100 // readonly修饰的n可以在初始化时修改值,在constructor里赋值都是初始化操作
    }
    static type = '哺乳动物'; // 静态属性,es6不支持,es7语法
    // static get type(){ // 属性访问器  es6的写法
    //     return '哺乳动物'
    // }
    static getName() {
        return '动物'
    }
    say() {
        console.log('父 ')
    }
}
// new Animal() // Animal的构造器被标识为protected和private,不能在外面new,会提示‘Constructor of class 'Animal' is protected/private and only accessible within the class declaration.’
class Cat extends Animal { // Animal的构造器被标识为private,不能被子类继承,会提示‘Cannot extend a class 'Animal'. Class constructor is marked as private.’
    constructor(name: string, age: number, public readonly address: string) {
        super(name, age); // 相当于Animal.call(this, name, age)
        // this.n = 100 // readonly修饰的n可以在初始化时修改值,但此处不是初始化操作,会报错‘Cannot assign to 'n' because it is a read-only property.’
    }
    static type = '猫科动物';
    static getName() {
        console.log(super.getName())
        return '猫'
    }
    say() { // 原型方法中的super指向的是父类的原型
        super.say()
    }
    private str: string = ''; // 编译成es5后,会变成Cat原型上的属性Cat.prototype.str = ''
    // str = '' // 编译后,会放在实例上,this.str = ''
    get content() { // 编译成es5后,会通过Object.defineProperty将content定义在Cat.prototype上
        return this.str
    }
    set content(newVal: string) {
        this.str = newVal
    }
    // aaaa = 1; //es7 语法 ts不建议使用 会作为实例方法
}
// 静态方法可以被继承  super 默认在构造函数中和静态方法中都指向自己的父类, 在原型方法中super指向父类的原型

// 原型方法直接写就是原型方法, 可以通过属性访问器定义原型属性
let cat = new Cat('Tom', 8, '美国');

console.log(cat.name)
cat.say();
cat.content = 'abc'
console.log(cat.content)

// 类的装饰器
// 接口
// 泛型
// 类型保护
// 交叉类型
// 兼容性
// 条件类型
// 内置方法
// 自定义类型
// 命名空间
// 声明文件