class
类的基本使用class
关键字定义一个类,本质上是一个function
,可以看做一个语法糖,定义了同一组对象(又称为实例)共有的属性和方法prototype
属性也是存在的,实际上所有的方法都是绑定在prototype
上面constructor
方法是类的默认方法,通过new
生成实例对象的时候就会被调用,一个类必须有constructor
方法,如果没有显式定义,一个空的constructor
就会被创建this
使用constructor
里面的 this
指向的是创建的实例对象class Person {
constructor(x,y){
// constructor 里面的this 指向的是创建的实例对象
this.x = x
this.y = y
}
sum(){
console.log(this.x + this.y)
}
}
const user = new Person(5,5)
user.sum() // 10
extends
和super
关键字)extends
关键字可以继承父类的方法,但是如果子类和父类中都存在同一个方法,会采取就近原则,调用子类的方法class Father {
star(){
console.log("Father 中的 star 的方法")
}
sing() {
console.log("Father 中的 sing 方法")
}
}
class Son extends Father{
sing() {
console.log("Son 中的 sing 方法")
}
}
const user = new Son()
user.star() // Father 中的 star 的方法
user.sing() // Son 中的 sing 方法
super
关键字,注意使用super
关键字的时候必须写在子类的this
之前调用class Father {
constructor(x,y) {
this.x = x
this.y = y
}
sum() {
console.log(this.x + this.y)
}
}
class Son extends Father{
constructor(x,y){
super(x,y)
this.x = x
this.y = y
}
}
const user = new Son(5,5)
user.sum() // 10