详细版原型链:
完整版原型链
1.ES5构造函数和ES6类的继承方式
// ES5 构造函数(超类构造函数)
function Person(name) {
this.name = name;
}
// ES6 类
class Person {
constructor(name) {
this.name = name;
}
}
// ES5 构造函数(子类构造函数)
function Student(name, studentId) {
// Call constructor of superclass to initialize superclass-derived members.
Person.call(this, name);
// Initialize subclass's own members.
this.studentId = studentId;
}
//继承了父类的prototype,获取了里面的构造器和方法
Student.prototype = Object.create(Person.prototype);
//但里面的constructor指向的是父级,也就是说,实例对象指向的是父类构造函数。
//因此为了让原型对象正确的指向自己,将constructor修改为Student,指向Student构造函数
Student.prototype.constructor = Student;
// ES6 类
class Student extends Person {
constructor(name, studentId) {
super(name);
this.studentId = studentId;
}
}