原型与原型链是初级前端必备技能,也是前端面高频面试题之一,在此记录一下。

class原型的本质

  • ES6 的 class 可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的 class 写法只是让对象原型的写法更加清晰、更像面向对象编程的语法
  • 类的本质是一个函数,类自身指向的就是构造函数
  • 原型链代码实例:
  1. //父类
  2. class People {
  3. constructor(name) {
  4. this.name = name;
  5. }
  6. walk() {
  7. console.log(this.name + "go to school");
  8. }
  9. }
  10. //子类
  11. class Student extends People {
  12. constructor(name, score, number) {
  13. super(name);
  14. this.score = score;
  15. this.number = number;
  16. }
  17. sayNice() {
  18. console.log(this.name + "是窝窝乡" + this.number + "妖侠");
  19. }
  20. }
  21. //子类
  22. class Teacher extends People {
  23. constructor(name, major) {
  24. super(name);
  25. this.major = major;
  26. }
  27. explain() {
  28. console.log(this.name + "教" + this.major);
  29. }
  30. }
  31. //声明实例
  32. let manji = new Student("蛮吉", "100", "001");
  33. console.log(manji.name);//蛮吉
  34. manji.sayNice(); //蛮吉是窝窝乡001妖侠
  35. manji.walk(); //蛮吉去挑战村长
  36. //声明实例
  37. let manxiaoman = new Teacher("蛮小满", "霸王冲");
  38. console.log(manxiaoman.name); //蛮小满
  39. manxiaoman.explain();//蛮小满教霸王冲
  40. manxiaoman.walk(); //蛮小满去挑战村长

原型链的图示

点击查看【processon】