1. (function () {
    2. // 定义一个表示人的类
    3. class Person {
    4. // Ts可以在属性前添加属性的修饰符
    5. /*
    6. public 修饰的属性可以在任意位置访问(修改) 默认值
    7. private 私有属性,私有属性只能在类内部进行访问(修改)
    8. 通过在类中添加方法使得私有属性可以被外部访问
    9. protected 受保护的属性,只能在当前类和当前类的子类中访问(修改)
    10. */
    11. private _name: string;
    12. private _age: number;
    13. constructor(name: string, age: number) {
    14. this._name = name;
    15. this._age = age;
    16. }
    17. // 定义方法,用来获取name属性
    18. /* getName() {
    19. return this.name;
    20. }
    21. // 定义方法,用来设置name属性
    22. setName(value: string) {
    23. if (value == '') {
    24. alert('不能修改')
    25. } else {
    26. this.name = value;
    27. }
    28. } */
    29. // Ts中设置getter方法的方式
    30. get name() {
    31. console.log('get name()执行了');
    32. return this._name
    33. }
    34. set name(val: string) {
    35. if (val != '') {
    36. this._name = val;
    37. }
    38. }
    39. }
    40. class A {
    41. protected num: number;
    42. constructor(num: number) {
    43. this.num = num;
    44. }
    45. }
    46. class B extends A{
    47. test() {
    48. console.log(this.num);
    49. }
    50. }
    51. const b = new B(123);
    52. // 错误:因为num加了protected修饰符,是受保护属性,只能被父类和其子类访问
    53. b.num;
    54. class C{
    55. // 可以直接将属性定义在构造函数中
    56. // 不用写this.name = name...
    57. constructor(public name: string, public age: number) {
    58. }
    59. }
    60. const per = new Person('zhangsan', 18);
    61. // per.getName();
    62. // per.setName('lisi');
    63. console.log(per);
    64. /*
    65. 现在的属性是在对象中设置的,属性可以任意的被修改
    66. 属性可以任意被修改将会导致对象中的数据变得非常不安全
    67. per.name = 'lisi';
    68. per.age = 38;
    69. */
    70. })()