11.构造函数继承.html 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. * 实现:
  13. * 在子类的构造函数中 用call/apply把父类的this指向子类的实例
  14. * 相当于把父类的属性全部复制一份
  15. * 优点:
  16. * 可以给父类进行传参
  17. * 父类中引用数据类型 不共享实例
  18. * 缺点:
  19. * 不能继承父类原型上的方法
  20. */
  21. function Person(name1) {
  22. this.name = name1;
  23. this.age = 3;
  24. this.list = ["吃饭", "睡觉", "打豆豆"];
  25. }
  26. Person.prototype.say = function () {
  27. console.log("hello");
  28. }
  29. function Child(name1) {
  30. Person.apply(this,[name1]);
  31. // Person.call(this,name1);
  32. };
  33. let c1 = new Child('图图');
  34. let c2 = new Child('喜羊羊');
  35. c1.list.push("玩耍");
  36. console.log(c1, 'c1')
  37. console.log(c2, 'c2')
  38. // c1.say(); // TypeError: c1.say is not a function
  39. </script>
  40. </body>
  41. </html>