博客列表 >class类的继承和常用API演示

class类的继承和常用API演示

          
          原创
2022年11月05日 09:31:56407浏览
  1. /*
  2. 作业内容:
  3. 1. 实例演示class类与extends,super等的用法
  4. 2. 实例演示字符串,数组常用API (至少5个以上)
  5. */
  6. // 一、实例演示class类与extends,super等的用法
  7. // 父类
  8. let Small_Head_Dad = class {
  9. // 构造函数:声明属性
  10. constructor(name) {
  11. this.name = name;
  12. // 技能
  13. this.sing = '会高歌一曲';
  14. this.cook = '一桌满汉全席';
  15. }
  16. // 方法
  17. say(){
  18. return this.name + this.sing
  19. }
  20. // 方法
  21. dinner(){
  22. return this.name + this.cook
  23. }
  24. }
  25. // 创建新对象
  26. let datou = new Small_Head_Dad('小头爸爸')
  27. // 输出父亲会唱歌
  28. console.log(datou.say())
  29. // 大头儿子继承唱歌 继承
  30. class Big_Head_Son extends Small_Head_Dad {
  31. constructor(name,sing,status) {
  32. // super 调用父类成员
  33. super(name,sing,status);
  34. // 子类扩展的属性
  35. this.status = '上学'
  36. }
  37. // 子类方法
  38. school(){
  39. return this.name + '还在'+this.status
  40. }
  41. // 子类方法
  42. skill(){
  43. return this.name + '会'+this.sing
  44. }
  45. }
  46. let son = new Big_Head_Son('大头儿子')
  47. // 儿子继承了父亲的唱歌方法
  48. console.log(son.say())
  49. // 子类方法
  50. console.log('子类方法1'+son.school())
  51. console.log('子类方法2'+son.skill())
  52. // 二、 实例演示字符串,数组常用API (至少5个以上)
  53. // replace()替换
  54. let arr = '今天天气怎么样?';
  55. console.log(arr.replace('怎么样?','晴朗!')) // 今天天气晴朗!
  56. // substring() 提取字符
  57. console.log(arr.substring(0,4)) // 今天天气
  58. // split() 字符串 -> 数组
  59. console.log(arr.split('怎')) // [ '今天天气', '么样?' ]
  60. // toString() 将数组转为字符串
  61. let arr2 = ['1','3','5','7']
  62. console.log(arr2.toString()) // ['1','3','5','7'] => 1,3,5,7
  63. // reverse() 翻转数组
  64. console.log(arr2.reverse()) // [ '7', '5', '3', '1' ]
  65. // push() 在末尾添加元素
  66. console.log(arr2.push('新增')) // 返回值是数组长度
  67. console.log(arr2) // [ '7', '5', '3', '1', '新增' ]
  68. // pop() 删除数组末尾的一个元素
  69. console.log(arr2.pop()) // 返回值是删除的那个元素
  70. console.log(arr2) // [ '7', '5', '3', '1' ]

运行结果

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议