typescript中类的继承

typescript中类的继承用到的是:extendssuperes6

先看一下typescript中类的写法:typescript

class Demo{
    //类的属性
    name:string;
    age:number;
    //类的构造函数
    constructor(name:string,age:number){
        this.name=name;
        this.age=age;
    }
    //类的方法
    run():string{
        return `${this.name}的年龄是${this.age}岁`
    }
}

其实至关于js中的构造函数:es5的写法能够和上面的es6的类对比一下函数

function Demo(name,age){
   //构造函数的属性 
this.name=name; this.age=age;
   //方法
this.run=function(){ return this.name+"的年龄是"+this.age+"岁" } } var demo=new Demo("张三",19); alert(demo.run());

下来看类的继承:this

class Tparent{
    name:string;//类的属性
    //类的构造函数
    constructor(name:string){
        this.name=name;
    }
    run():string{
        return `${this.name}在运动`
    }
}

用一个Web类来继承上面的类es5

class Web extends Tparent{
    constructor(name:string){
        super(name);//至关于初始化父类的构造函数
    }
}

var w=new Web("李四");
alert(w.run());
相关文章
相关标签/搜索