6.属性的封装.ts 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. (function() {
  2. class Person {
  3. /**
  4. * readonly 只读
  5. * static 类本身 而不是类对象
  6. * public 公开
  7. * private 私有的 类内部可以访问
  8. * protected 受保护的 类的内部和子类均可访问
  9. */
  10. name: string;
  11. private age: number;
  12. protected color:string;
  13. constructor(name:string,age:number,color:string) {
  14. this.name = name;
  15. this.age = age;
  16. this.color = color;
  17. }
  18. get age1() {
  19. return this.age;
  20. }
  21. set age1(val) {
  22. this.age = val;
  23. }
  24. getValue() {
  25. return this.age + 10;
  26. }
  27. }
  28. class Child extends Person {
  29. look() {
  30. console.log(this.color)
  31. }
  32. }
  33. let p = new Person("孙悟空",20,'红色');
  34. let c = new Child('图图',2,'白色');
  35. p.age1 = 30;
  36. console.log(p.age1)
  37. // console.log(p.age);
  38. // console.log()
  39. c.look();
  40. console.log(p.getValue())
  41. // console.log(c.color);
  42. })()