前言
● 下面是一段之前学习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();