public(公开的)
- 如果使用
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
来修饰属性, 那么表示这个属性是受保护的- 可以在类的内部使用, 也可以在子类中使用
错误示例:
正确示例:
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
来修饰属性, 那么表示这个属性是私有的- 可以在类的内部使用
错误示例:
正确示例:
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(只读的)
错误示例:
正确示例:
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
不能使用,其它的都是可以进行使用的,博主就不演示了