类与Object.create之间的继承

前言

● 下面是一段之前学习Object.create的一段代码

const PersonProto = {
  calcAge() {
    console.log(2037 - this.birthYear);
  },

  init(firstName, birthYear) {
    this.firstName = firstName;
    this.birthYear = birthYear;
  }
};

const zhangsan = Object.create(PersonProto);
● 和之前一样,我们创建学生的继承

const PersonProto = {
  calcAge() {
    console.log(2037 - this.birthYear);
  },

  init(firstName, birthYear) {
    this.firstName = firstName;
    this.birthYear = birthYear;
  }
};

const zhangsan = Object.create(PersonProto);

const StudentProto = Object.create(PersonProto);
const ITshare = Object.create(StudentProto);
ITshare.init('ITshare', 2005);

在这里插入图片描述

● 和之前一样,学生的类可以添加新的方法

const PersonProto = {
  calcAge() {
    console.log(2037 - this.birthYear);
  },

  init(firstName, birthYear) {
    this.firstName = firstName;
    this.birthYear = birthYear;
  }
};

const zhangsan = Object.create(PersonProto);

const StudentProto = Object.create(PersonProto);
StudentProto.init = function (firstName, birthYear, course) {
  PersonProto.init.call(this, firstName, birthYear);
  this.course = course;
};
const ITshare = Object.create(StudentProto);
ITshare.init('ITshare', 2005, '计算机科学与技术');

在这里插入图片描述

● 像之前一样,写一段介绍的方法,可以调用原型链中的方法

//对象继承
const PersonProto = {
  calcAge() {
    console.log(2037 - this.birthYear);
  },

  init(firstName, birthYear) {
    this.firstName = firstName;
    this.birthYear = birthYear;
  }
};

const zhangsan = Object.create(PersonProto);

const StudentProto = Object.create(PersonProto);
StudentProto.init = function (firstName, birthYear, course) {
  PersonProto.init.call(this, firstName, birthYear);
  this.course = course;
};

StudentProto.introduce = function () {
  console.log(`我的名字叫${this.firstName},我的专业是${this.course}`);
};
const ITshare = Object.create(StudentProto);
ITshare.init('ITshare', 2005, '计算机科学与技术');

ITshare.introduce();
ITshare.calcAge();

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值