属性修饰符
| 修饰符 | 含义 | 具体规则 |
|---|---|---|
| public | 公开的 | 可以被:类内部、子类、类外部访问 。 |
| protected | 受保护的 | 可以被:类内部、子类访问。 |
| private | 私有的 | 可以被:类内部访问。 |
| readonly | 只读属性 | 属性无法修改。 |
public 修饰符
Person 类
typescript
class Person {
// name写了public修饰符,age没写修饰符,最终都是public修饰符
public name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
speak() {
// 类的【内部】可以访问public修饰的name和age
console.log(`我叫:${this.name},今年${this.age}岁`);
}
}
const p1 = new Person("张三", 18);
// 类的【外部】可以访问public修饰的属性
console.log(p1.name);Student 继承 Person
typescript
class Student extends Person {
constructor(name: string, age: number) {
super(name, age);
}
study() {
// 【子类中】可以访问父类中public修饰的:name属性、age属性
console.log(`${this.age}岁的${this.name}正在努力学习`);
}
}属性的简写形式
完整写法
typescript
class Person {
public name: string;
public age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}简写形式
typescript
class Person {
constructor(public name: string, public age: number) {}
}protected 修饰符
Person 类
typescript
class Person {
// name和age是受保护属性,不能在类外部访问,但可以在【类】与【子类】中访问
constructor(protected name: string, protected age: number) {}
// getDetails是受保护方法,不能在类外部访问,但可以在【类】与【子类】中访问
protected getDetails(): string {
// 类中能访问受保护的name和age属性
return `我叫:${this.name},年龄是:${this.age}`;
}
// introduce是公开方法,类、子类、类外部都能使用
introduce() {
// 类中能访问受保护的getDetails方法
console.log(this.getDetails());
}
}
const p1 = new Person("杨超越", 18);
// 可以在类外部访问introduce
p1.introduce();
// 以下代码均报错
// p1.getDetails()
// p1.name
// p1.ageStudent 继承 Person
typescript
class Student extends Person {
constructor(name: string, age: number) {
super(name, age);
}
study() {
// 子类中可以访问introduce
this.introduce();
// 子类中可以访问name
console.log(`${this.name}正在努力学习`);
}
}
const s1 = new Student("tom", 17);
s1.introduce();private 修饰符
typescript
class Person {
constructor(
public name: string,
public age: number,
// IDCard属性为私有的(private)属性,只能在【类内部】使用
private IDCard: string
) {}
private getPrivateInfo() {
// 类内部可以访问私有的(private)属性 —— IDCard
return `身份证号码为:${this.IDCard}`;
}
getInfo() {
// 类内部可以访问受保护的(protected)属性 —— name和age
return `我叫: ${this.name}, 今年刚满${this.age}岁`;
}
getFullInfo() {
// 类内部可以访问公开的getInfo方法,也可以访问私有的getPrivateInfo方法
return this.getInfo() + "," + this.getPrivateInfo();
}
}
const p1 = new Person("张三", 18, "110114198702034432");
console.log(p1.getFullInfo());
console.log(p1.getInfo());
// 以下代码均报错
// p1.name
// p1.age
// p1.IDCard
// p1.getPrivateInfo()readonly 修饰符
typescript
class Car {
constructor(
public readonly vin: string, //车辆识别码,为只读属性
public readonly year: number, //出厂年份,为只读属性
public color: string,
public sound: string
) {}
// 打印车辆信息
displayInfo() {
console.log(`
识别码:${this.vin},
出厂年份:${this.year},
颜色:${this.color},
音响:${this.sound}
`);
}
}
const car = new Car("1HGCM82633A123456", 2018, "黑色", "Bose音响");
car.displayInfo();
// 以下代码均错误:不能修改 readonly 属性
// car.vin = '897WYE87HA8SGDD8SDGHF';
// car.year = 2020;
