思维导图自取
image.png
image.png
image.png
image.png

实现

image.png

通过原型链来实现继承

image.png
例子

  1. <script>
  2. // 父类,人类
  3. function People(name, age, sex) {
  4. this.name = name;
  5. this.age = age;
  6. this.sex = sex;
  7. }
  8. People.prototype.sayHello = function () {
  9. console.log('你好,我是' + this.name + '我今年' + this.age + '岁了');
  10. };
  11. People.prototype.sleep = function () {
  12. console.log(this.name + '开始睡觉,zzzzz');
  13. };
  14. // 子类,学生类
  15. function Student(name, age, sex, scholl, studentNumber) {
  16. this.name = name;
  17. this.age = age;
  18. this.sex = sex;
  19. this.scholl = scholl;
  20. this.studentNumber = studentNumber;
  21. };
  22. // 关键语句,实现继承
  23. Student.prototype = new People();
  24. Student.prototype.study = function () {
  25. console.log(this.name + '正在学习');
  26. };
  27. Student.prototype.exam = function () {
  28. console.log(this.name + '正在考试,加油!');
  29. };
  30. // 实例化
  31. var hanmeimei = new Student('韩梅梅', 9, '女', '慕课小学', 100556);
  32. hanmeimei.study();
  33. hanmeimei.sayHello();
  34. hanmeimei.sleep();
  35. </script>

image.png
并且子类是可以重写父类的方法的

  1. // 重写、复写(override)父类的sayHello
  2. Student.prototype.sayHello = function () {
  3. console.log('敬礼!我是' + this.name + '我今年' + this.age + '岁了');
  4. }