一、认识Class定义类
在ES6以前,我们常使用一个函数来定义类,我们可以把类理解成一个函数,ES6新增Class关键字来定义类。
1.ES5使用function来定义类
function Person(name,age){
this.name = name,
this.age = age,
this.running= function(){
console.log(this.name + "running~")
}
}
const per = new Person("XM",13)
per.running() //调用Person类中的方法
由上图可知,我们使用function来定义了一个Person类,这个类中有属性,有方法,接下来我们利用class来实现同样的效果。
2.利用Class定义类
既然ES6新推出了Class,那么它一定有它的优势,接下来我们看一下属性和方法如何在Class定义的中添加。
class Student{
constructor(name,age){
this.name = name,
this.age = age
}
running(){
console.log("running~")
}
static studying(){
console.log("I`m studying~")
}
}
const stu1 = new Student("小明","10")
stu1.running() //打印running~
Student.studying() //打印I`m studying~,类的静态方法static,可以通过类名直接调用,如果上面没有使用static关键字,则此处会报错
- constructor函数:与function定义类不同的是,Class中使用constructor函数来给类添加属性,Student所有的属性都写在constructor中。
-
static静态方法:上述代码可以看到多了一个static,而它的后面跟的也是一个方法,我们把static称作静态添加方法。从上面两个图片的代码中我们可以看出来,不管是function还是Class定义的方法,都需要利用new出来的实例对象(对应per、stu1)来调用方法,而我们在方法前添加一个static关键字,该方法就能通过类名来直接调用了。
注意:在Class定义的类添加方法时,直接写上方法名即可,与function的一个小区别。
二、ES6类的继承
在一个类中可能有多个方法和属性,那么如果多个类使用相同的方法和属性,每次定义类都写一次,会影响运行的性能,因此ES6推出了extends来实现属性和方法的继承。(ES6之前使用原生js进行逻辑操作实现继承,这里不再赘述)
1.使用extends实现继承,super关键字决定要继承的属性
class Teacher {
constructor(name,age){
this.name = name,
this.age = age
}
running(){
console.log(this.name + "running~")
}
eating(){
console.log("eating~")
}
}
//定义子类,extends代表Student继承自Teacher
class Student extends Teacher{
constructor(name,age,sno,score){
super(name,age) //super表示要继承哪些属性
this.sno = sno,
this.score = score
}
running(){
console.log("跑步使我快乐!") //对继承的内容进行修改
}
}
const stu1 = new Student("小明","88")
stu1.eating() //打印eating
stu1.running() //打印跑步使我快乐
- super关键字:super决定了要继承哪些属性,同时需要注意,super必须要写,且一定要写在this的前面,如果没有继承的话也要写一个super(),不能省略。
-
super(name,age) //相当于this.name = name,this.age = age