JavaScript学习笔记-Class(ES6)
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){ |
用class 构建:
javascript
class Student{ |
实例化:
javascript
var xiaoming = new Student('小明'); |
class继承
利用class继承非常方便,直接通过 extends
来实现:
javascript
class PrimaryStudent extends Student{ |
注意 PrimaryStudent
的定义也是 class
关键字实现的,而 extends
则表示原型链对象来自 Student
。
子类的构造函数可能会与父类不太相同,例如, PrimaryStudent
需要 name
和 grade
两个参数,并且需要通过 super(name)
来调用父类的构造函数,否则父类的 name
属性无法正常初始化。
PrimaryStudent
已经自动获得了父类 Student
的 hello
方法,我们又在子类中定义了新的 myGrade
方法。
for python:
python
class PrimaryStudent(Student): |
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Comment