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

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. function Person(name1) {
  21. this.name = name1;
  22. this.age = 3;
  23. this.list = ["吃饭", "睡觉", "打豆豆"];
  24. }
  25. Person.prototype.say = function () {
  26. console.log("hello");
  27. }
  28. function Child(name1) {
  29. Person.apply(this,[name1]);
  30. // Person.call(this,name1);
  31. };
  32. let c1 = new Child('图图');
  33. let c2 = new Child('喜羊羊');
  34. c1.list.push("玩耍");
  35. console.log(c1, 'c1')
  36. console.log(c2, 'c2')
  37. // c1.say(); // TypeError: c1.say is not a function
  38. </script>
  39. </body>
  40. </html>