博客列表 >实现类的继承,使用原生,es6各写一遍-Es6-50课9.4

实现类的继承,使用原生,es6各写一遍-Es6-50课9.4

希望
希望原创
2020年09月12日 11:43:51611浏览

1、类的继承:原生

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>类的继承:原生</title>
  7. </head>
  8. <body>
  9. <script>
  10. // 原生是通过修改原型链来实现继承
  11. // 1.父类
  12. function Vehicle(fuel, purpose) {
  13. this.fuel = fuel;
  14. this.purpose = purpose;
  15. }
  16. // 公共/原型方法
  17. Vehicle.prototype.show = function () {
  18. return `燃料: ${this.fuel}\n用途: ${this.purpose}\n`;
  19. };
  20. console.dir(Vehicle);
  21. // 2. 子类
  22. function Car(fuel, purpose, color) {
  23. // this是当前子类
  24. Vehicle.call(this, fuel, purpose);
  25. this.color = color;
  26. }
  27. // 关键代码
  28. // 更新当前子类的原型对象,这样才能实现真正意义上继承
  29. Car.prototype = Object.create(Vehicle.prototype);
  30. // 手工补上constructor
  31. Car.prototype.constructor = Car;
  32. // 在子类中重写父类的原型方法
  33. Car.prototype.show = function () {
  34. return Vehicle.prototype.show
  35. .call(this)
  36. .concat(`颜色: ${this.color}\n`);
  37. };
  38. // 实例化子类
  39. const car = new Car("汽油", "商用", "白色");
  40. console.log(car.show());
  41. </script>
  42. </body>
  43. </html>

2、类的继承:es6

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>类的继承:es6</title>
  7. </head>
  8. <body>
  9. <script>
  10. // 父类
  11. class Vehicle {
  12. // 构造方法
  13. constructor(fuel, purpose) {
  14. this.fuel = fuel;
  15. this.purpose = purpose;
  16. }
  17. // 原型方法
  18. show() {
  19. return `燃料: ${this.fuel}\n用途: ${this.purpose}\n`;
  20. }
  21. }
  22. // 子类
  23. class Car extends Vehicle {
  24. constructor(fuel, purpose, color) {
  25. // 调用父类的构造方法
  26. // super()必须是第一条,否则不能正确的生成子类的this
  27. super(fuel, purpose);
  28. this.color = color;
  29. }
  30. // 重写父类的原型方法
  31. show() {
  32. // super:代表父类的原型对象
  33. console.log(super.show === Vehicle.prototype.show);
  34. return super.show().concat(`颜色: ${this.color}\n`);
  35. }
  36. // super:
  37. // 1. 当成函数: super()代表父类的构造方法,必须用在子类的构造方法中的第一行
  38. // 2. 当成对象: super用在原型方法/静态方法,代码父类的原型对象
  39. }
  40. // 实例化子类
  41. const car = new Car("新能源", "商用", "绿色");
  42. console.log(car.show());
  43. </script>
  44. </body>
  45. </html>
  • 总结:
  • es6实现类的继承,用到的super:代表父类的原型对象,调用父类的构造方法时,super()必须是第一条,才能在外部访问到子类
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议