JS类的继承

继承:子类可以继承父类的一些属性和方法
extends关键字表示实现子类继承父类的属性和方法;
super关键字用于访问和调用对象父类上的函数,可以调用父类的构造函数,也可以调用父类的普通函数;

let that
let _that
class Father { // 父类
	constructor (x, y) {
		this.x = x
		this.y = y
		this.say() // father
	}
	sum() {
		console.log(this.x + this.y)
	}
	say() {
		return 'father'
	}
} 
class Son extends Father { // 子类继承父类
	constructor (x, y) {
		super(x, y) // 调用父类的构造函数,必须先调用父类构造方法再使用子类构造方法
		this.x = x
		this.y = y
		that = this
	}
	say() {
		super.say() // 调用父类的普通函数
	}
	substract() {
		_that = this // this指向实例对象
		console.log(this.y - this.x) // 子类继承父类加法的同时扩展减法方法
	}
} 
const son1 = new Son(1, 2)
son1.sum() // 3
son1.say() // father
son1.substract() // 1
console.log(that === son1) // true
console.log(_that === son1) // true
  • 在ES6中类没有变量提升,所以必须先定义类,才能通过类实例化对象;
  • 类里面的的共有属性和方法一定要加this使用;
  • 类里面的this的指向问题,constructor里面的this指向创建的实例对象;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值