一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第7天,点击查看活动详情。
类
类是面向对象程序设计实现信息封装的基础,就比如人类他就是一个类,每个人都有相同的形态,如都有姓名、性别、都会说话、吃饭。我们将具有相同属性和行为,但是属性的值不一样,比如每个人的姓名都不一样,这样chuxian就是一个类,每个人比如你我都只人类这一类的的具体实物,在TS中对应的就是类的实例。
类的大概结构如下图:
class Person {
// 类的静态成员
static displayName: string = 'person'
// 类的成员属性
public name: string;
private age: number;
protected tel: string;
public readonly id: number;
// 类的构造函数
constructor(id: number, name: string, age: number, tel: string) {
this.id = id;
this.name = name;
this.age = age;
this.tel = tel;
}
// 类的成员方法
getName() {
console.log(this.age);
return "我的名字叫" + this.name;
}
}
// 创建类的实例对象
const greeter = new Person(1, '小明', 12, '1131231');
greeter.getName();
修饰符
类中常用的修饰符public、privite、protected、readonly、static。主要用于对类成员的访问限制,和常用的面向对象语言都基本一样。
public: 公共的,修饰的变量或者方法可以再子类、实类对象上访问, 没有修饰符默认是public。
privite: 私有的,只能在当前类中访问,不能再子类或者实例对象上访问。
protected: 受保护的,能再子类中访问但是不能在实例对象上访问。
readonly: 只读,顾名思义修饰的变量不能修改,不能再方法上进行修饰。可以和上面三种修饰符同时修饰放到他们之后。
static: 静态,修改时类的静态成员,通过类直接访问,实例对象上不能访问。
class Student extends Person {
// 类的构造函数
constructor(id: number, name: string, age: number,tel: string) {
super(id, name, age, tel)
}
// 类的成员方法
getInfo() {
return {
id: this.id,
name: this.name,
// age: this.age, // 错误,无法访问到age,因为是私有变量子类不能使用
tel: this.tel
}
}
setId() {
// this.id = '121313123'; // 错误,tel是只读的不能修改
}
}
const stu = new Student(1, '小明', 12, '1131231');
// console.log(stu.age); // 错误,无法访问到age
// console.log(stu.tel); // 错误,无法访问到tel
console.log(Person.displayName); // person
console.log(Student.displayName); // 错误,静态成员无法继承
继承和实现接口
继承就是继承一个父类,如上面的类中学生类student继承了person类就会带有person类提供的成员,子类也可以覆盖父类的成员,比如上面的getName方法,在子类中重新写一个就是所谓的重载。 实现接口其实是对接口的实现,接口是类成员的类型约束,类根据约束实现这些类型的值。
interface Person {
name: string,
getName: () => string
}
class Man implements Person {
name: string; // 如果不定义namez则会报错
constructor(name: string) {
this.name = name;
}
getName(): string {
return this.name;
}
}
抽象类
抽象类介于类和接口之间,既可以定义类的成员,也可以给成员赋值,但是它和类也有不同,他不能被实例化。使用 abstract关键字定义。
class Student extends Person {
name: string = '11'; // 报错
getName(): string {
return this.name;
}
}
const stu = new Student();
补充
- 快捷构造方法定义初始化成员变量,不用一个一个this.xx = xx
class Man implements Person {
constructor(public name: string)
}
const man = new Man('ss');
man.name; // ss
- 类表达式写法,和函数表达式写法类似.
const Person = class {
constructor(public name: string){}
}