TypeScript中的类、继承、三种修饰符

1.ts中的类的定义

// class Person {
//     name: string;    //属性   前面省略public
//     constructor(name: string) {  //构造函数   实例化类的时候触发的方法
//         this.name = name;


//     }
//     run(): void {
//         console.log('我是ts中的方法')
//     }
// }
// var o = new Person('李四');
// o.run();

2.ts中的类的继承

// class Person {
//     name: string;    //属性   前面省略public
//     constructor(name: string) {  //构造函数   实例化类的时候触发的方法
//         this.name = name;


//     }
//     run(): void {
//         console.log('我是ts中的方法.')
//     }
// }
// // 子类
// class Web extends Person{
//     constructor(name:string){
//         super(name)
//     }
//     // 子类自己的方法
//     work(){
//         console.log(this.name+'在工作')
//     }
//     run(){
//         console.log(this.name+'运动')
//     }
// }

// var w = new Web('李四');
// // console.log(w.name)
// w.work();
// w.run();   //先在子类找方法,加入没有才到继承的父类去找

3.ts中的三种修饰符(ts中定义属性的时候,提供了三种修饰符)

/*
public  表示公有(在类里面和子类里面、以及类外面都可以访问)
protected    保护类型(类和子类里面可以访问,类外面不可以访问)
private      表示私有(类外面和子类不可以访问)
属性不加修饰符  默认共有属性public
*/
    // public
        // class Person {
        //    public name: string;    //属性   前面省略public
        //     constructor(name: string) {  //构造函数   实例化类的时候触发的方法
        //         this.name = name;


        //     }
        //     run(): void {
        //         console.log('我是ts中的方法.')
        //     }
        // }
        // var o = new Person('哈哈哈')
        // console.log(o.name)   //哈哈哈
    // protected
        // class Person {
        //     protected name: string;    //属性   前面省略public
        //     constructor(name: string) {  //构造函数   实例化类的时候触发的方法
        //         this.name = name;


        //     }
        //     run(): void {
        //         console.log('我是ts中的方法.')
        //     }
        // }
        // var o = new Person('哈哈哈')
        // console.log(o.name)   //ts报错(只能在Person及子类使用)
    // private
        // class Person {
        //    private name: string;    //属性   前面省略public
        //     constructor(name: string) {  //构造函数   实例化类的时候触发的方法
        //         this.name = name;


        //     }
        //     run(): void {
        //         console.log('我是ts中的方法.')
        //     }
        // }
        // class Web extends Person{
        //     constructor(name:string){
        //         super(name)
        //     }
        //     run():void{
        //         console.log(this.name + '工作')   //报错(私有属性,只能在Person中访问)
        //     }
        // }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值