前言
TypeScript 的类属性修饰符是一种重要的语言特性,用于控制类成员的可访问性和行为。主要有三种修饰符:public、private 和 protected。
public(公开的)
代码语言:typescript复制如果使用
public
来修饰属性, 那么表示这个属性是公开的 可以在类的内部使用, 也可以在子类中使用, 也可以在外部使用 默认情况下就是public
的
class Person {
public name: string;
age: number;
gender: string;
constructor(name: string, age: number, gender: string) {
this.name = name;
this.age = age;
this.gender = gender;
}
say(): void {
console.log(`name=${this.name},age=${this.age},gender=${this.gender}`);
}
}
class Student extends Person {
constructor(name: string, age: number, gender: string) {
super(name, age, gender);
}
say(): void {
console.log(`name=${this.name}`);
}
}
let p = new Person('BNTang', 18, 'male');
p.say();
console.log(p.name);
let stu = new Student('zs', 18, 'female');
stu.say();
console.log(stu.name);
protected(受保护的)
如果使用
protected
来修饰属性, 那么表示这个属性是受保护的 可以在类的内部使用, 也可以在子类中使用
错误示例:
正确示例:
代码语言:typescript复制class Person {
name: string;
protected age: number;
gender: string;
constructor(name: string, age: number, gender: string) {
this.name = name;
this.age = age;
this.gender = gender;
}
say(): void {
console.log(`name=${this.name},age=${this.age},gender=${this.gender}`);
}
}
class Student extends Person {
constructor(name: string, age: number, gender: string) {
super(name, age, gender);
}
say(): void {
console.log(`age=${this.age}`);
}
}
let p = new Person('BNTang', 18, 'male');
p.say();
let stu = new Student('zs', 18, 'female');
stu.say();
private(私有的)
如果使用
private
来修饰属性, 那么表示这个属性是私有的 可以在类的内部使用
错误示例:
正确示例:
代码语言:typescript复制class Person {
name: string;
age: number;
private gender: string;
constructor(name: string, age: number, gender: string) {
this.name = name;
this.age = age;
this.gender = gender;
}
say(): void {
console.log(`name=${this.name},age=${this.age},gender=${this.gender}`);
}
}
class Student extends Person {
constructor(name: string, age: number, gender: string) {
super(name, age, gender);
}
say(): void {
}
}
let p = new Person('BNTang', 18, 'male');
p.say();
let stu = new Student('zs', 18, 'female');
stu.say();
readonly(只读的)
错误示例:
正确示例:
代码语言:typescript复制class Person {
name: string;
age: number;
readonly gender: string;
constructor(name: string, age: number, gender: string) {
this.name = name;
this.age = age;
this.gender = gender;
}
say(): void {
console.log(`name=${this.name},age=${this.age},gender=${this.gender}`);
}
}
class Student extends Person {
constructor(name: string, age: number, gender: string) {
super(name, age, gender);
}
say(): void {
}
}
let p = new Person('BNTang', 18, 'male');
p.say();
console.log(p.gender);
let stu = new Student('zs', 18, 'female');
stu.say();
注意点:关于静态属性和静态方法只有 readonly
不能使用,其它的都是可以进行使用的,博主就不演示了
最后
本期结束咱们下次再见