typescript中类的继承

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

先看一下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());

下来看类的继承:

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

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

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

var w=new Web("李四");
alert(w.run());

猜你喜欢

转载自www.cnblogs.com/longailong/p/10573292.html