博客列表 >实例演示class类与extends,super的用法

实例演示class类与extends,super的用法

皮皮志
皮皮志原创
2022年11月05日 15:24:38617浏览
  1. // 先声明一个类
  2. let User = class{
  3. // 构造函数 声明属性
  4. constructor(name,age){
  5. // 1.实例成员
  6. this.name = name
  7. this.age = age
  8. }
  9. // 2.方法
  10. sayHello(){
  11. return `你好,我是${this.name},今年${this.age}岁,性别${User.gender},我是${User.country}人`
  12. }
  13. // 在类中添加静态成员
  14. static gender = "男";
  15. }
  16. // 在类外添加静态成员
  17. User.country = "China"
  18. // 实例化
  19. const user = new User('阿狗', 27)
  20. console.log(user);
  21. console.log(user.sayHello());
  22. console.log("----------------------");
  23. // extends 继承
  24. class Child extends User {
  25. constructor(name,age,hobby){
  26. super(name,age)
  27. // 子类扩展属性 hobby
  28. this.hobby = hobby
  29. }
  30. sayHello(){
  31. return `${super.sayHello()},我的爱好是${this.hobby}`
  32. }
  33. }
  34. const child = new Child("二狗",18,"打飞机")
  35. console.log(child.sayHello());
  36. console.log('=====================');
  37. // 字符串常用api
  38. let str = "我爱的人不是我的爱人";
  39. // 1.取长度
  40. console.log(str.length);
  41. // 2.查询成员的索引
  42. console.log(str.indexOf('爱'));
  43. // 爱出现了两次 只返回第一个查到的值 若想查到所有的索引 可看下列代码
  44. function findAll(Str,str) {
  45. let res =[],
  46. len =Str.length,
  47. index=0
  48. while(index < len){
  49. // 由于我需要将str每个都传入进去 所以我需要将索引也进行更新
  50. index = Str.indexOf(str,index)
  51. if(index === -1){
  52. break;
  53. }
  54. res.push(index)
  55. index ++
  56. }
  57. return res
  58. }
  59. console.log(findAll(str,"爱"));
  60. // 3.替换 replace
  61. let str1 = str.replace('爱',"不爱")
  62. console.log(str1);
  63. // 批量替换 replaceAll
  64. let str2 = str.replaceAll('爱',"不爱")
  65. console.log(str2);
  66. // 4.寻找索引的值 substring()
  67. console.log(str.substring(1,3));
  68. console.log(str.substring(5,3));
  69. // 5.字符串 转 数组 split
  70. let str3 = str.split("")
  71. console.log(str3);
  72. // 例子
  73. let Phone = class{
  74. #founder = 'Q';
  75. constructor(name,price){
  76. this.name = name
  77. this.price = price
  78. }
  79. introduce(){
  80. return `这款手机名叫${this.name},他的价格是${this.price},我们现在有iphone${Phone.PhoneModel}的型号`
  81. }
  82. who(){
  83. return `CE0${this.#founder}`
  84. }
  85. changeCEO(founder){
  86. this.#founder = founder
  87. }
  88. static PhoneModel =[4,5,6,7,8,9,10,11,12,13,14]
  89. }
  90. const phone = new Phone()
  91. console.log(phone.who());
  92. phone.changeCEO("k")
  93. console.log(phone.who());
  94. class Phone13 extends Phone{
  95. constructor(name,price,inventory){
  96. super(name,price)
  97. this.inventory = inventory
  98. }
  99. introduce(){
  100. return `${super.introduce()},库存还有${this.inventory}部`
  101. }
  102. }
  103. const phone13 = new Phone13('iphone13','8000',500)
  104. console.log(phone13.introduce());
  105. console.log(phone13.founder);//无法访问父类的私有属性 返回undefined
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议