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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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(x) {
  21. this.address = x;
  22. this.name = '图图';
  23. this.age = 3;
  24. this.list = ['吃饭', '睡觉', '打豆豆'];
  25. }
  26. Person.prototype.say = function () {
  27. console.log("你好")
  28. }
  29. function Child(val) {
  30. console.log(val,'val')
  31. // Person.call(this,val)
  32. Person.apply(this,[val])
  33. }
  34. let c1 = new Child('北京');
  35. let c2 = new Child('哈尔滨');
  36. c2.list.push("12");
  37. console.log(c1, 'c1', c1.list)
  38. console.log(c2, 'c2', c2.list)
  39. c1.say()
  40. </script>
  41. </body>
  42. </html>