public private protected
|
类 |
外部 |
子类 |
| private |
可以访问 |
可以访问 |
不可访问 |
| public |
可以访问 |
不可访问 |
不可访问 |
| private |
可以访问 |
不可访问 |
可以访问 |
class Person{ // 使用private修饰的变量在类外部是不可读取的 private name:string = "lisi"; public age:number = 20;}var p:Person= new Person();console.log(p);console.log(p.age);p.age = 30;console.log(p);
protected 修饰的变量在类外部不能访问class Student{ protected name:string = "lisi" sayName(){ console.log(this.name); }}var s:Student = new Student();// console.log(s.name);
private protected区别
protected在子类中protected可以访问,private不可访问
class Student{ protected name:string = "lisi" sayName(){ console.log(this.name); }}class MidStudent extends Student{ getName(){ console.log(this.name); }}var m:MidStudent = new MidStudent();m.getName();