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>构造函数继承</title>
    7. </head>
    8. <body>
    9. </body>
    10. </html>
    11. <script>
    12. /**
    13. * 优点:
    14. * 创建的子类,可以向父类传参
    15. * 缺点:
    16. * 每个实例都拷贝一份,占内存大
    17. * 只能继承父类构造函数的属性和方法,不能继承父类原型上的属性和方法;
    18. */
    19. function Person(id) {
    20. this.id = id || 'id not';
    21. this.fun = function(id){
    22. return `只能继承原型上的属性和方法 - ${id}`;
    23. }
    24. // 原型上的属性和方法
    25. Person.prototype = {
    26. value: '不能继承原型上的属性和方法',
    27. get() {
    28. console.log('penson get');
    29. }
    30. }
    31. }
    32. function Adult(id) {
    33. this.type = '子类';
    34. // 给父类传参
    35. Person.call(this, id)
    36. }
    37. // 给父类传参
    38. const adult = new Adult('前端伪大叔');
    39. console.log(adult); // __proto__: Object 没有继承 Person原型~ 直接找到了 Object原型上
    40. // 调用父类的属性和方法
    41. console.log(adult.id);
    42. console.log(adult.fun('id'));
    43. // 因为只是实现了构造函数继承,所有无法使用原型上的属性和方法
    44. console.log(adult.value); // undefined
    45. console.log(adult.get()); // Uncaught TypeError: adult.get is not a function
    46. </script>