24.继承2.0.html 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. * 2.构造函数的继承(call/apply)
  12. *
  13. */
  14. function Father() {
  15. this.name = 'LiLi';
  16. this.color = 'red';
  17. this.arr = [1,2,3];
  18. this.fn1 = function() {
  19. console.log("这是第一个方法");
  20. }
  21. }
  22. Father.prototype.getColor = function() {
  23. return this.color;
  24. }
  25. function Child() {
  26. Father.call(this);
  27. }
  28. let newChild = new Child();
  29. newChild.fn1();
  30. console.log(newChild);
  31. let a1 = new Child();
  32. let a2 = new Child();
  33. a1.name += 10;
  34. a2.name += 20;
  35. a2.arr.push(10);
  36. console.log(a1,'a1');
  37. console.log(a2,'a2');
  38. /**
  39. * 构造函数继承可以解决原型链继承的同时修改引用数据类型的缺点
  40. * 可以使用父级构造函数上的属性和方法
  41. * 不可以使用父级原型上的属性和方法
  42. */
  43. console.log(newChild.getColor());
  44. </script>
  45. </body>
  46. </html>