Typescript 第五章 类的声明,继承

【1】类的声明和实例化

##1

//类声明
class Person1{
    name;

     eat(){
        console.log('im eating');
    }
}
//类的实例化
var p1=new Person1();
p1.name='batman';
p1.eat();

var p2=new Person1();
p2.name='superman';
p2.eat();

##2 访问控制符

//访问控制符 public private protected
class Person1{
   protected name;//属性“name”受保护,只能在类“Person1”及其子类中访问

    private eat(){ //属性“eat”为私有属性,只能在类“Person1”中访问
        console.log('im eating');
    }
}

var p1=new Person1();
p1.name='batman';//报错
p1.eat();

var p2=new Person1();
p2.name='superman';
p2.eat();

【2】类的构造函数

##1

class Person2{
    constructor(){  //类被实例化的时候调用,外部不能访问,new时访问
        console.log("lddd")
    }
     name;

     eat(){
        console.log('im eating');
    }
}
var p3=new Person2();
p3.name='batman';
p3.eat();

##2

class Person3{
    name;
    constructor(name:string){  //实例化时制定名字
       this.name=name;
    }
    eat(){
        console.log('im eating');
    }
}
var p4=new Person3("李四");
p4.eat();

简化代码:

class Person3{
   
    constructor(public name:string){  //实例化时制定名字,明确要声明访问控制符
      
    }
    //public name:string和 name:string,不一样

    eat(){
        console.log('im eating');
    }
}
var p4=new Person3("李四");
p4.eat();

【3】类的继承

##1,extends,用来声明类的继承关系

//类的继承 extends
class Person5{
    constructor(public name:string){  //明确要声明访问控制符
        console.log('hahah')
    }
    eat(){
        console.log('im eating');
    }
}

class Employee extends Person5{
    code:string;//指定新的属性和方法
    work(){
    }
}

var e1=new Employee('xiaoli');
e1.eat();
e1.work();

##2,super用来调用父类的构造函数或者方法

【1】调用父类的构造函数

class Person6{
    constructor(public name:string){  //明确要声明访问控制符
        console.log('hahah')
    }
    eat(){
        console.log('im eating');
    }
}
class Employee2 extends Person6{
    code:string;
    constructor(name:string,code:string){
        super(name);//调用父类的构造函数
        this.code=code;
        console.log('xxx');
    }
    work(){
      
    }
   
}
var e3=new Employee2('banman','4556566');//hahah,xixi

【2】用来调父类的其他的方法 super.

class Person6{
    constructor(public name:string){  //明确要声明访问控制符
        console.log('hahah')
    }
    eat(){
        console.log('im eating');
    }
}
class Employee2 extends Person6{
    constructor(name:string,code:string){
        super(name);//调用父类的构造函数
        this.code=code;
        console.log('xxx');
    }
    code:string;
    work(){
        super.eat();
        this.doWork();
    }
    private doWork(){
        console.log('im working');
    }

}
var e3=new Employee2('banman','4556566');
e3.work(); //hahah,xixi,im eating,im working



你可能感兴趣的:(typescript)