如果想在外部访问私有成员变量,就可以利用set方法
//申明类class Person {//属性,成员变量public name: string = "张三";public age: number;//私有成员private _job: string = "IT";//受保护的成员变量protected house: string = "这是一个好房子";//构造函数,创建对象会默认调用的方法constructor(name: string, age: number) {this.name = name;this.age = age;}//从外部间接访问私有成员set job(job: string) {console.log("当前set方法执行了")this._job = job;}get job(): string {return this._job;}//定义方法,成员方法//成员变量,成员方法只能由当前对象调用,当前类无法直接调用sayHello(msg: string = "默认信息"): void {console.log(this.name + msg);//仅能在当前class类中使用私有成员变量console.log(this._job);}}//student继承当前person类的方法与属性class Student extends Person {//这里是学生自己的属性gender: string;constructor(name: string, age: number, gender: string) {//调用父类的构造函数初始化name和age的信息//这里的super一定在第一个super(name, age);//初始化自己的gender信息this.gender = gender;}sayHello(msg: string = "默认信息"): void {//利用super调用父类的方法super.sayHello();//打印当前子类的信息,因为get,所以现在可以访问私有成员变量console.log("当前性别是:", this.gender,this.job);}}let p1 = new Person("王苏", 20);p1.sayHello();let p2 = new Student("王兄下", 23, "男");p2.sayHello();let stu=new Student("小明",21,"男")//这里修改job相当于给set方法传递了一个参数stu.job="teacher"stu.sayHello()
