本文主要是介绍类与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();
这篇关于类与Object.create之间的继承的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!