JS 中的class
类的基本使用
1. 基本使用 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
2. 类的继承(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