『TypeScript』类

1. ts 中类的定义

class Person{
    name!:string;
    age:number;

    constructor(name:string, age:number) {
        this.name = name;
        this.age = age;
    }
    running(){
        console.log(this.name + " running")
    }
    eating(){
        console.log(this.name + " eating")
    }
}

let p = new Person("ES6+",7)
p.running()
p.eating()

2. ts 类的类型

let p2: A = {
    name: "p two",
    age: 18,
    running(){},
    eating(){}
}

3. ts 类的继承 extends

// error Classes can only extend a single class.
// class Student extends Person, A{}
// -------------------------------
class Student extends Person{
    learn: string;
    constructor(name:string, age:number, learn: string) {
        super(name, age);
        this.learn = learn
    }
    running(){
        //this ==> s
        //super===> Person
        super.running()
        console.log(this.name + " Student running")
    }
}

4. ts 类的成员修饰符

在typeScript中 类的属性和方法支持三种修饰符

1 public 修饰的属性或方法是公有的,可以在任何地方被访问到,默认的是 public 
2 private 修饰的属性或方法是私有的,不能在声明它的类的外部访问(不参与继承)
3 protected 修饰的属性或方法是受保护的,在子类中也是允许被访问的
4 readonly 修饰的是这个属性我们不希望外界可以任意的修改,只希望确定值之后直接使用(只能读)

 1. public

class Person{
    public name!:string;
    public age:number;
    // ...
}
class Student extends Person{
    public learn: string;
    constructor(name:string, age:number, learn: string) {
        super(name, age);
        this.learn = learn
    }
    running(){
        //this ==> s
        //super===> Person
        super.running()
        console.log(this.name + " Student running") // studentStudent running
    }
}

let s: Student = new Student("student", 18, "TypeScript");
s.running();
console.log(s) // Student { name: 'student', age: 20, learn: 'TypeScript' }

2. private

class Person{
    private name:string;
    constructor(name:string) {
        this.name = name;
    }
}

let p = new Person("aa"); // {name: 'a'}

3. protected

class Person{
    protected name:string;
    constructor(name:string) {
        this.name = name;
    }
}

let p = new Person("aa");
// error Property 'name' is protected and only accessible within class 'Person' and its subclasses.
console.log("=======>",p.name)

4. readonly

class Person{
    readonly name:string;
    constructor(name:string) {
        this.name = name;
    }
}

let p = new Person("aa");

// p.name = '123123'; // error Cannot assign to 'name' because it is a read-only property.

console.log(p.name); // 'aa'

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值