It has been 1485 days since the last update, the content of the article may be outdated.

之前的原型继承关系可以看出,JS在实现继承时还是很麻烦的,需要大量代码。
但是,class出现了。

class

class从ES6开始正式被引入到JavaScript中,目的就是让定义类更简单。

先前的类方法:

javascript
function Student(name){
this.name=name;
}

Student.prototype.hello= function(){
alert("Hello, "+this.name);
}

用class 构建:

javascript
class Student{
constructor(name){
this.name=name;
}

hello(){
alert('Hello, '+this.name);
}
}

实例化:

javascript
var xiaoming = new Student('小明');
xiaoming.hello();

class继承

利用class继承非常方便,直接通过 extends 来实现:

javascript
class PrimaryStudent extends Student{
constructor(name,name){
supper(name);
this.grade=grade;
}

myGrade(){
alert(this.name+" your grade is "+this.grade);
}
}

注意 PrimaryStudent 的定义也是 class 关键字实现的,而 extends 则表示原型链对象来自 Student
子类的构造函数可能会与父类不太相同,例如, PrimaryStudent 需要 name grade 两个参数,并且需要通过 super(name) 来调用父类的构造函数,否则父类的 name 属性无法正常初始化。

PrimaryStudent 已经自动获得了父类 Student hello 方法,我们又在子类中定义了新的 myGrade 方法。

for python:

python
class PrimaryStudent(Student):
def __init__(self,name,grade):
super(PrimaryStudent,self).__init__(name)
self.grade=grade

def hello(self):
print("hello, ",self.name)