类和构造函数之间的继承

类之间构造函数的继承是面向对象编程中的一个重要概念,它允许一个类(子类)继承另一个类(父类)的属性和方法。通过这种方式,子类可以复用父类的代码,从而避免重复,提高代码的可维护性和可读性。
在这里插入图片描述

● 例如下面的代码,已经存在了一个生成姓名和一个计算年龄的构造函数

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();

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值