12.组合继承.html 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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>Document</title>
  7. </head>
  8. <body>
  9. <script>
  10. /**
  11. * 组合继承:原型链 + 构造函数
  12. * 实现:call/apply + 原型链
  13. * 优点:
  14. * 解决原型链继承父类无法传参
  15. * 解决了原型链中父类共享实例
  16. * 解决了构造函数继承无法继承父类原型上的方法
  17. * 缺点:父类的构造函数被调用了两次 代码冗余
  18. */
  19. function Person(name1) {
  20. this.name = name1;
  21. this.age = 3;
  22. this.list = ["吃饭", "睡觉", "打豆豆"];
  23. }
  24. Person.prototype.say = function () {
  25. console.log("hello");
  26. }
  27. function Child(name1) {
  28. // 1.构造函数继承
  29. Person.apply(this,[name1]);
  30. };
  31. // 2.原型链继承
  32. Child.prototype = new Person();
  33. // 修改构造函数的指向
  34. Child.prototype.constructor = Child;
  35. Child.prototype.say1 = function() {
  36. console.log("hi");
  37. }
  38. let c1 = new Child('图图');
  39. let c2 = new Child('喜羊羊');
  40. c1.list.push("玩耍");
  41. console.log(c1, 'c1')
  42. console.log(c2, 'c2')
  43. c1.say();
  44. c1.say1();
  45. </script>
  46. </body>
  47. </html>