基于构造函数+原型链的继承

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>Document</title>
    8. </head>
    9. <body>
    10. <script>
    11. // 父类
    12. function Father(uname,age){
    13. this.uname = uname;
    14. this.age = age;
    15. // this指向 Father实例出来的对象
    16. }
    17. Father.prototype = {
    18. constructor:Father,
    19. eat:function(){
    20. console.log('吃饭');
    21. },
    22. speak:function(){
    23. console.log('说话');
    24. }
    25. }
    26. // 子类
    27. function Son(uname,age,like,weight){
    28. // (1)利用 call 方法,改变Father构造函数内的this指向,从而实现属性的继承。
    29. Father.call(this,uname,age);
    30. this.like = like;
    31. this.weight = weight;
    32. }
    33. // (2)让 Son.prototype.__proto__ 指向 Father.prototype,就可以实现方法的继承
    34. Son.prototype = new Father();
    35. Son.prototype.constructor = Son;
    36. // 扩展子类的方法
    37. Son.prototype.skill = function(){
    38. console.log('我会计算机');
    39. }
    40. var son1 = new Son('jon',18,['玩游戏','运动'],'70kg')
    41. son1.speak();
    42. </script>
    43. </body>
    44. </html>