ts中类的修饰符

1. 访问修饰符

用于设置类中变量和方法的访问权限
public(默认): 公有,可以在任何地方被访问
protected : 受保护,只在当前类和其子类中被访问(在类的外部无法被访问)
private : 私有,只在当前类中可以被访问(在子类中或者类的外部都无法被访问)

class Person {
 public name: string;
 protected age: number;
 private sex: string;
 constructor(name: string, age: number, sex: string) {
 this.name = name;
 this.age = age;
 this.sex = sex;
 }
 public show(): void {
 console.log(this.name + this.sex + this.age);
 }
}
let alias = new Person("alias", 18, "女");
console.log(alias);
console.log(alias.name);
// 1. 被 protected 或者 private 修饰的变量或者属性,在类的外部无法被访问
// console.log(alias.age); // protected 权限限制,此属性不可被访问
// console.log(alias.sex); // private 权限限制,此属性不可被访问
alias.show();
class Student extends Person {
 grade: string;
 constructor(name: string, age: number, sex: string, grade: string) {
 super(name, age, sex);
 this.grade = grade;
 }
 show(): void {
 // 1. 在父类中被 private 修饰的变量或者属性,在子类中无法被访问
 console.log(this.name + this.age /*+ this.sex */ + this.grade);
 }
}
let xiaoming = new Student("小明同学", 12, "男", "五年级");
console.log(xiaoming);
// 2. 在父类中被 protected 或者 private 修饰的变量或者属性,在继承它的子类的外部也无法被访问
// console.log(xiaoming.age); // 父类 protected 权限限制,此属性不可被访问
// console.log(xiaoming.sex); // 父类 private 权限限制,此属性不可被访问
xiaoming.show();

常用于保护成员变量,暴露成员方法:
用 private 或 protected 保护成员变量(不让它在外部被修改,只能通过 get,set 方法或者实例化时被修改),用 public 修饰成员方法(对外暴露)

2. 只读修饰符(readonly)

只能在变量初始化 或者 constructor 构造函数中给 readonly 修饰的属性赋值。只可读,不可修改。

class Student {
 name: string;
 readonly age: number;
 readonly sex: string = "男"; // 赋值位置一
 constructor(name: string, age: number) {
 this.name = name;
 this.age = age; // 赋值位置二,同时赋值:位置二会覆盖位置一
 }
}
let alias = new Student("alias", 18);
alias.name = "小明";
// alias.age = 100; // 只读 阻止再次赋值
console.log(alias);
作者:high-profile 原文地址:https://segmentfault.com/a/1190000042625441

%s 个评论

要回复文章请先登录注册