类之间构造函数的继承是面向对象编程中的一个重要概念,它允许一个类(子类)继承另一个类(父类)的属性和方法。通过这种方式,子类可以复用父类的代码,从而避免重复,提高代码的可维护性和可读性。
● 例如下面的代码,已经存在了一个生成姓名和一个计算年龄的构造函数
const Person = function (firstName, birthYear) {
this.firstName = firstName;
this.birthYear = birthYear;
};
Person.prototype.calcAge = function () {
console.log(2028 - this.birthYear);
};
● 现在有个学生函数需要继承Person的属性并且自己也有自己独特的方法
const Person = function (firstName, birthYear) {
this.firstName = firstName;
this.birthYear = birthYear;
};
Person.prototype.calcAge = function () {
console.log(2028 - this.birthYear);
};
const Student = function (firstName, birthYear, course) {
this.firstName = firstName;
this.birthYear = birthYear;
this.course = course;
};
const Sun = new Student('Sun', 1999, '计算机科学与技术');
console.log(Sun);
● 现在我们在学生的函数中添加相关的方法
const Person = function (firstName, birthYear) {
this.firstName = firstName;
this.birthYear = birthYear;
};
Person.prototype.calcAge = function () {
console.log(2028 - this.birthYear);
};
const Student = function (firstName, birthYear, course) {
this.firstName = firstName;
this.birthYear = birthYear;
this.course = course;
};
Student.prototype.introduce = function () {
console.log(`我叫${this.firstName},我学习的专业是${this.course}`);
};
const Sun = new Student('Sun', 1999, '计算机科学与技术');
Sun.introduce();
● 上面的代码看起来很好,但是违反了重复性原则,而且构造函数中的代码变动并不会体现在Student函数中,我们可以这样修改
const Person = function (firstName, birthYear) {
this.firstName = firstName;
this.birthYear = birthYear;
};
Person.prototype.calcAge = function () {
console.log(2028 - this.birthYear);
};
const Student = function (firstName, birthYear, course) {
Person.call(this, firstName, birthYear);
this.course = course;
};
Student.prototype.introduce = function () {
console.log(`我叫${this.firstName},我学习的专业是${this.course}`);
};
const Sun = new Student('Sun', 1999, '计算机科学与技术');
Sun.introduce();
● 原理分析
● 但是我们发现我们我们无法调用构造函数的内部方法
Sun.calcAge();
● 通过对象继承
const Person = function (firstName, birthYear) {
this.firstName = firstName;
this.birthYear = birthYear;
};
Person.prototype.calcAge = function () {
console.log(2028 - this.birthYear);
};
const Student = function (firstName, birthYear, course) {
Person.call(this, firstName, birthYear);
this.course = course;
};
//链接原型
Student.prototype = Object.create(Person.prototype);
Student.prototype.introduce = function () {
console.log(`我叫${this.firstName},我学习的专业是${this.course}`);
};
const Sun = new Student('Sun', 1999, '计算机科学与技术');
Sun.introduce();
Sun.calcAge();