一、基础语法
class Person {
constructor() {
}
}
二、类的属性
1、属性的初始化
在 TS 中,我们如果在要 constructor 中定义一个属性,必须先在 constructor 之前对数据进行初始化:
class Person {
city: string; // 初始化
constructor() {
this.city = '成都'
}
}
属性在初始化的时候可以选择不设置初始值,但是就必须在 constructor 中进行赋值。
也可以在初始化的时候就设置一个初始值:
class Person {
city: string = '四川'; // 初始化
constructor() {
//
}
}
2、属性的传值
class Person {
city: string = '四川';
name: string;
constructor(name: string) {
this.city = '成都'
this.name = name;
}
}
new Person('Lee');
3、静态属性
class Person {
static country: string = '中国'
city: string = '四川';
name: string;
constructor(name: string) {
this.city = '成都'
this.name = name;
}
}
new Person('Lee');
三、类的方法
class Person {
static country: string = '中国'
city: string = '四川';
name: string;
constructor(name: string) {
this.city = '成都'
this.name = name;
}
// sayHello(name: string): void {
// console.log('hello' + name);
// }
sayHello = (name: string): void => {
}
}
new Person('Lee');
四、类的继承
class Person {
static country: string = '中国'
city: string = '四川';
name: string;
constructor(name: string) {
this.city = '成都'
this.name = name;
}
// sayHello(name: string): void {
// console.log('hello' + name);
// }
sayHello = (name: string): void => {
}
}
class Student extends Person {
constructor(name: string) {
super(name);
}
}
子类的 constructor 中如果没有其他额外的属性,可以省略不写:
class Student extends Person {
}
如果子类有自己的属性:
class Student extends Person {
age: number;
constructor(name: string) {
super(name);
this.age = 20;
}
}
五、访问修饰符
访问修饰符,用来修饰类里面的属性和方法:
修饰符 | 含义 | 作用范围 |
---|---|---|
public(默认) | 公共类型 | 当前类、子类、外部 |
protected | 受保护类型 | 当前类、子类 |
private | 私有类型 | 当前类 |
readonly | 只读类型 | 当前类、子类、外部 |
示例代码:
class Person {
protected city: string = '成都'
}
const p = new Person();
console.log(p.city);
私有类型的 getter 和 setter(扩展)
class Person {
private _city: string = '成都'
get city() {
return this._city;
}
set city(value: string) {
if (value === '四川') {
this._city = value;
}
}
}
const p = new Person();
console.log(p.city);
p.city = '四川';