一、创建一个类
constructor
函数在创建实例化对象的时候,就进行调用
class Car {
// 构造器方法
constructor(name, price) {
// 构造器中的this--类的实例对象
this.name = name
this.price = price
}
// 一般方法
// 这个方法放在了类的原型对象上,供实例使用
// 通过Car的实例调用该方法时,this指向的就是Car的实例对象
drive() {
console.log(`我开${this.name}牌汽车`)
}
}
// 创建Car的实例对象
const c1 = new Car('奔驰', '50w')
const c2 = new Car('宝马', '40w')
-
通过赋值语句创建的方法,是放在实例自身上的,调用通过
实例对象名.方法名
-
直接声明的方法,是放在原型对象上的,调用通过
实例对象名.方法名
- 如果方法前面用
static
进行修饰,这个方法时放在类的本身上的,调用通过类名.方法名
class Car {
drive() {
console.log('这个方法放在了原型对象上')
}
fun = ()=> {
console.log('这个方法放在了实例自身上')
}
static fun1 = ()=> {
console.log('我前面用static进行修饰, 我是加在类本身的方法上的方法')
}
static fun2() {
console.log('我前面用static进行修饰, 我是加在类本身的方法上的方法')
}
}
const c1 = new Car()
c1.drive()
c1.fun()
Car.fun1()
Car.fun2()
二、继承
1.全部继承自父类
class Bus extends Car {}
const b1 = new Bus('解放', '10W')
console.log(b1)
// Bus { name: '解放', price: '10W' }
b1.drive()
// 我开解放牌汽车
2. super关键字
// 继续上面的例子
class Bus extends Car {
constructor(name, price, load) {
super(name, price)
this.load = load
}
}
const b1 = new Bus('解放', '10W', '20t')
console.log(b1)
// Bus { name: '解放', price: '10W', load: '20t' }
super
关键字只能放在构造器函数最前面执行
2.1 类中的继承关系
// 继续上面的例子
b1.drive()
// 我开解放牌汽车
此时,b1
的原型对象Bus上并没有drive
方法,因此通过原型链向上找到Car
原型对象,Car
的原型上有drive
,因此,此时b1
是通过原型链调用的Car
上的方法
class Bus extends Car {
constructor(name, price, load) {
super(name, price)
this.load = load
}
drive() {
console.log(`我开${this.name}牌汽车,我的载重是${this.load}`)
}
}
const b1 = new Bus('解放', '10W', '20t')
b1.drive()
// 我开解放牌汽车,我的载重是20t
此时,b1
的原型对象Bus上有drive
方法,因此,b1
调用的就是他原型对象上的drive
方法
2.2 super调用父类中的普通函数
class Car {
constructor(name, price) {
this.name = name
this.price = price
}
drive() {
return `我是${this.name}牌汽车,我的价格是${this.price}`
}
}
class Bus extends Car {
constructor(name, price, weight) {
super(name, price)
this.weight = weight
}
drive() {
console.log(super.drive() + ',我的载重是' + this.weight)
}
}
const b1 = new Bus('解放', '10w', '10t')
b1.drive()
在子类的普通函数中,可以通过super.父类函数名()
,来调用父类中的普通函数