TypeScript中的class

js中的class类

    class Parent {
        constructor(x) {
            this.x = x;
            this.sayHello = function () {
                console.log("sayHello")
            }
        }
        getX() {
            console.log("getX==>", this.x)
        }
    }

ts中的class类

//class 类 传值必须定义类型和值
class Person {
    name!: string; // js中不用定义 ts中需要定义
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
    running() {
        console.log(this.name)
    }
    eating() {
        console.log(this.age)
    }
}
let p = new Person("小白", 666)
p.running()
p.eating()
console.log(p);

类中的修饰符

1 public  [ˈpʌblɪk]   公有属性方法 --- 修饰的是在任何地方可见 公有的属性或方法 默认编写的属性就是public的

2 private  [ˈpraɪvət]  不需要的值写上就不用继承 --- 修饰的是仅在同一类中可见 私有的属性或方法(不参与继承)

3 protected [prəˈtektɪd] 不能读和写 --- 修饰的是仅在类自身及子类中可见 受保护的属性或方法(不能读写)

4 readonly [ˌriɑˈdɔnli]  只读 --- 修饰的是这个属性我们不希望外界可以任意的修改,只希望确定值之后直接使用(只能读)

5.static   [ˈstætɪk]  --- 静态成员 无法实例化 不能用实例调用 用构造函数调用

类的继承

//父类
class Person {
    name!: string; // Ts中需要定义
    age: number;

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

class Student extends Person{
    str: string;
    constructor(name:string, age:number, str: string) {
        super(name, age); // 继承要写super
        this.str = str
    }
    running(){
        // this指向当前构造函数的实例就是 s的this
        //supe --- Person.running()
        super.running()
        console.log(this.name + "哈哈哈")
    }
}

let s: Student = new Student("小白", 666, "ts"); 
s.running();
s.eating();
console.log(s)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值