一、面向对象
封装、继承、多态
1-1 封装函数
api 应用程序接口 封装复杂,接口简单
class Person{ name:string; age;number; constructor(name:string,age:number){ this.name = name; this.age = age } sayName(){ console.log(this.name); }}
1-2 extends 继承
/* 1、定义一个Person类,包含name,age两个属性 */class Person{ name:string; age;number; constructor(name:string,age:number){ this.name = name; this.age = age } sayName(){ console.log(this.name); }}/* 2、student skill,saySkill *//* class Student{ name:string; age;number; skill:string; constructor(name:string,age:number,skill:string){ this.name = name; this.age = age this.skill = skill; } saySkill():void{ console.log(this.skill); }} */class Student extends Person{ skill:string; constructor(name:string,age:number,skill:string){ /* super指的是父类,只能放在子类构造方法中的第一行 */ super(name,age); this.skill = skill; } saySkill():void{ console.log(this.skill); }}var res:Student = new Student("lisi",18,"vue");console.log(res);res.sayName();
1-3 多态
根据传入的对象,动态决定调用谁的方法
interface Animal{ eat():void;}class Cat implements Animal{ eat():void{ console.log("鱼"); }}class Dog implements Animal{ eat():void{ console.log("骨头"); }}class Farmer{ feed(obj:Animal){ obj.eat() }}var f:Farmer = new Farmer();f.feed(new Cat())f.feed(new Dog())
二、接口到底是什么
2-1 抽象类
/* 抽象类 *//* 1、使用class关键字定义的叫实体类 *//* class Animal{ eat():void{ console.log("any"); }} *//* 2、抽象类 本质上就是一个接口 */abstract class Animal{ abstract eat():void}/* 使用实体类对抽象类实现继承的时候,必须重写抽象类中的抽象方法 */class Cat extends Animal{ eat():void{ console.log("鱼"); }}
interface Animal{ eat():void;}class Cat implements Animal{ eat():void{ console.log("鱼"); }}
三、修饰符public,private,protected
| 访问权限 |
类 |
外部 |
子类 |
| public |
√ |
√ |
√ |
| private |
√ |
× |
× |
| protected |
√ |
× |
√ |
//protectedclass Student{ protected name:string = "lisi"; sayName(){ console.log(this.name); }}var s:Student = new Student();console.log(s.name);
class Student{ protected name:string = "lisi"; sayName(){ console.log(this.name); }}/* protected和private的区别:在子类中 protected可以访问 private不可以访问*/class MidStundet extends Student{ getName(){ console.log(this.name); }}var m:MidStundet = new MidStundet();m.getName()