1. class People {
    2. private name: string;
    3. private age: number;
    4. constructor(name: string, age: number) {
    5. this.name = name;
    6. this.age = age;
    7. }
    8. setName(name: string) {
    9. this.name = name;
    10. }
    11. getName() {
    12. return this.name;
    13. }
    14. setAge(age: number) {
    15. this.age = age;
    16. }
    17. getAge() {
    18. return this.age;
    19. }
    20. }
    21. const p = new People("zhangsan", 18);
    22. p.setAge(20);
    23. console.log(p.getAge());

    这样封装,都要调用setXXX()getXXX()方法。

    为了方便,提供了一种简便的封装。但是这种方法,<font style="color:#DF2A3F;">set</font>``<font style="color:#DF2A3F;">get</font>后面的方法名不能与属性名相同。

    1. class People {
    2. private _name: string;
    3. constructor(name: string) {
    4. this.name = name;
    5. }
    6. set name(name: string) {
    7. console.log("set name");
    8. this._name = name;
    9. }
    10. get name() {
    11. console.log("get name");
    12. return this._name;
    13. }
    14. }
    15. const p = new People("zhangsan");
    16. p.name = "lisi";
    17. console.log(p.name);