ES6 解释子类和继承
子类: 子类是从另一个被称为父类的类的属性和方法派生而来的类。子类允许我们在不影响父类的情况下改变或更新父类的属性。子类可以包含父类的属性,同时我们也可以在子类中定义新的属性。
在上面的图片中, GeeksforGeeks 类将作为 Officials 和 Geeks 类的父类。 Officials 和 Geeks 类将作为子类,并从父类 GeeksforGeeks 继承一些属性和方法。
为了将父类的属性提供给子类,我们使用继承: 继承是一种通过使用另一个类为其提供一些新的属性和值来扩展类的方式,而不会干扰它本身。继承可以通过两种方式进行:
- 原型继承
- 使用extends关键字进行继承
原型继承: 原型继承使用 prototype 关键字进行。原型继承是继承的 es5 语法。
语法:
function func_name(){
// Content of func_name()
}
func_name.prototype.func_name2(){
// Content of func_name2()
}
示例: 下面的示例展示了使用 prototype 关键字来实现继承。
JavaScript
function GeeksforGeeks(name, desc) {
this.name = name;
this.desc = desc;
}
GeeksforGeeks.prototype.Officials = function Officials() {
console.log("I'm an Official.");
console.log("Community name is: ", this.name);
};
GeeksforGeeks.prototype.Geeks = function Geeks() {
console.log("I'm an Geek.");
console.log("Community description is: ", this.desc);
};
var GFG = new GeeksforGeeks(
"GeeksforGeeks",
"A computer science portal for all geeks."
);
GFG.Officials();
GFG.Geeks();
输出:
使用 extends 关键字的继承:es6 或者 ECMAScript-2015 引入了使用 extends 关键字继承父类属性的概念。我们会在子类中使用 super() 方法来调用父类的构造函数。
语法:
// Code for the parent class
class parent_class{
constructor(){
// Body of constructor
}
}
// Code for the child or sub class
class sub_class **extends** parent_class{
constructor(){
super()
// Body of constructor
}
}
示例:
Javascript
class GeeksforGeeks {
constructor(name, desc) {
this.name = name;
this.desc = desc;
}
getCommunityName() {
return this.name;
}
getCommunityDescription() {
return this.desc;
}
}
class Courses extends GeeksforGeeks {
constructor(communityName, communityDesc,
courseName, courseDesc) {
super(communityName, communityDesc);
this.c_name = courseName;
this.c_desc = courseDesc;
}
printValues() {
// You can also use 'this' keyword in place
// of 'super' to access properties and
// methods of parent class
console.log('The name of Community is: ',
super.getCommunityName());
console.log('The description of Community is: ',
super.getCommunityDescription());
console.log('The name of Course is: ', this.c_name);
console.log('The description of Course is: ', this.c_desc);
}
}
const GFG = new Courses(
'GeeksforGeeks',
'A computer science portal for all geeks.',
'DSA - Self Paced Course',
'A complete guide to Data Structures and Algorithms.',
);
GFG.printValues();
输出: