TS class类

extends 继承

class Animal {
  move() {
    console.log("走路");
  }
}
class Dog extends Animal {
  name = "二哈";
  bark() {
    console.log("汪汪");
  }
}
const d = new Dog();
d.move();
d.bark();

implements

使用implements后类中必须有接口中的属性和方法

interface Singable {
  sing(): void;
}
class Person implements Singable {
  sing(): void {
    console.log("继承Singable");
  }
}

public 公开:所有成员可访问(默认为public)

protected 受保护:内部成员及子类可访问

private 私有的:只有内部成员可访问

class Animal {
    public name:string
    protected move() {
        console.log("走路");
    }
    private age:number
    run(){
        this.move()
        this.age=20
        console.log('跑起来');
    }
}
class Dog extends Animal {
  name = "二哈";
  bark() {
    console.log("汪汪");
    this.move()
  }
}
const d = new Dog();
d.run();
d.name='修狗';

readonly: 表示只读,用来防止在构造函数之外对属性进行赋值(只能修饰属性,不能修饰方法)

class Person {
// 如果不添加类型age会是字面量类型
  readonly age: number = 18;
  constructor(age: number) {
    this.age = age;
  }
}
// 接口中使用readonly
interface Iperson {
  readonly name: string;
}
let obj: Iperson = {
  name: "jiom",
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值