class extends constructor static super get/set

    1. {
    2. // 基本定义和生成实例
    3. class Parent {
    4. constructor(name = "wcd") {
    5. this.name = name;
    6. }
    7. }
    8. let v_parent = new Parent("v");
    9. console.log("构造函数和实例", v_parent); // 构造函数和实例 Parent { name: 'v' }
    10. }
    11. {
    12. // 继承
    13. class Parent {
    14. constructor(name = "wcd") {
    15. this.name = name;
    16. }
    17. }
    18. class Child extends Parent {}
    19. console.log("继承", new Child()); // 继承 Child { name: 'wcd' }
    20. }
    21. {
    22. // 继承传递参数
    23. class Parent {
    24. constructor(name = "wcd") {
    25. this.name = name;
    26. }
    27. }
    28. class Child extends Parent {
    29. constructor(name = "child") {
    30. super(name);
    31. this.type = "child";
    32. }
    33. }
    34. console.log("继承传递参数", new Child("hello")); // 继承传递参数 Child { name: 'hello', type: 'child' }
    35. }
    36. {
    37. // getter, setter
    38. class Parent {
    39. constructor(name = "wcd") {
    40. this.name = name;
    41. }
    42. // 这里是属性,不是方法
    43. get longName() {
    44. return "yx" + this.name;
    45. }
    46. set longName(value) {
    47. this.name = value;
    48. }
    49. }
    50. let v = new Parent();
    51. console.log("getter", v.longName); // getter yxwcd
    52. v.longName = "hello";
    53. console.log("setter", v.longName); // setter yxhello
    54. }
    55. {
    56. // 静态方法,不能在类的实例上调用静态方法,而应该通过类本身调用
    57. class Parent {
    58. constructor(name = "wcd") {
    59. this.name = name;
    60. }
    61. static tell() {
    62. console.log("tell"); // tell
    63. }
    64. }
    65. Parent.tell();
    66. }
    67. {
    68. // 静态属性
    69. class Parent {
    70. constructor(name = "wcd") {
    71. this.name = name;
    72. }
    73. static tell() {
    74. console.log("tell");
    75. }
    76. }
    77. Parent.type = "test";
    78. console.log("静态属性", Parent.type); // 静态属性 test
    79. }