详细版原型链:

2.原型、原型链 - 图3

完整版原型链image.png

1.ES5构造函数和ES6类的继承方式

  1. // ES5 构造函数(超类构造函数)
  2. function Person(name) {
  3. this.name = name;
  4. }
  5. // ES6 类
  6. class Person {
  7. constructor(name) {
  8. this.name = name;
  9. }
  10. }
  11. // ES5 构造函数(子类构造函数)
  12. function Student(name, studentId) {
  13. // Call constructor of superclass to initialize superclass-derived members.
  14. Person.call(this, name);
  15. // Initialize subclass's own members.
  16. this.studentId = studentId;
  17. }
  18. //继承了父类的prototype,获取了里面的构造器和方法
  19. Student.prototype = Object.create(Person.prototype);
  20. //但里面的constructor指向的是父级,也就是说,实例对象指向的是父类构造函数。
  21. //因此为了让原型对象正确的指向自己,将constructor修改为Student,指向Student构造函数
  22. Student.prototype.constructor = Student;
  23. // ES6 类
  24. class Student extends Person {
  25. constructor(name, studentId) {
  26. super(name);
  27. this.studentId = studentId;
  28. }
  29. }