【前端】Javascript高级篇-类的继承

   日期:2020-05-30     浏览:140    评论:0    
核心提示:继承普通方法// 父类class Father { constructor() { } say() { console.log(hello world) }}// 子类class Son extends Father{ }// 通过子类调用父类方法var son = new Son()son.say()C:\\Users\\lenovo\\Downloads\\HBuilderX\\readme>cd C:\\Users\\lenovo\\Downloads\\HBjavascript

文章目录

    • 继承普通方法
    • 继承extend计算
  • super关键字-调用父类函数
    • 调构造函数
    • 调普通函数
      • 方法重写,就近调用
      • 子方法中调父普通函数
      • 继承父类方法同时扩展子类方法

继承普通方法

// 父类
class Father {
	constructor() {
	    
	}
	say() {
		console.log('hello world')
	}
}
// 子类
class Son extends Father{
	
}
// 通过子类调用父类方法
var son = new Son()
son.say()

C:\Users\lenovo\Downloads\HBuilderX\readme>cd C:\Users\lenovo\Downloads\HBuilderX\readme && C:\Users\lenovo\Downloads\HB
uilderX\plugins\node\node.exe demo.js
hello world

继承extend计算

错误示范,引出super

实例的this指向的数值,是子类传入的,限制在子类中。
而sum方法在父类中获取的是父类的实例this的值。
子传入的值,无法赋值给父类实例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) {
	    this.x = x
		this.y = y
	}
}
// 通过子类调用父类方法
var son = new Son()
son.sum(1,2)

super关键字-调用父类函数

调构造函数

super可以调用对象父类上的函数(包含构造函数)

// 父类
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) //调用了父类的构造函数
	}
}
// 通过子类调用父类方法
var son = new Son(1,2)
son.sum()

调普通函数

方法重写,就近调用

子类继承的方法重写之后,就近原则,先调用子类方法

// 父类
class Father {
	constructor(x,y) {
	    this.x = x
		this.y = y
	}
	say() {
		console.log('father')
	}
}
// 子类
class Son extends Father{
	say() {
		console.log('son')
	}
}
// 通过子类调用父类方法
var son = new Son()
son.say()

son

子方法中调父普通函数

// 父类
class Father {
	constructor(x,y) {
	    this.x = x
		this.y = y
	}
	say() {
		console.log('father')
	}
}
// 子类
class Son extends Father{
	say() {
		console.log(super.say() + ' son')
	}
}
// 通过子类调用父类方法
var son = new Son()
son.say()

father son

继承父类方法同时扩展子类方法

// 父类
class Father {
	constructor(x,y) {
	    this.x = x
		this.y = y
	}
	add() {
		console.log(this.x + this.y)
	}
}
// 子类继承父类加法,同时扩展减法
class Son extends Father{
	constructor(x,y) {
		// super调用父方法,必须在构造方法顶部调用
		super(x,y)
	    this.x = x
		this.y = y
	}
	substract() {
		console.log(this.x - this.y)
	}
}
// 通过子类调用父类方法
var son = new Son(5,3)
son.add()
son.substract()

C:\Users\lenovo\Downloads\HBuilderX\readme>cd C:\Users\lenovo\Downloads\HBuilderX\readme && C:\Users\lenovo\Downloads\HB
uilderX\plugins\node\node.exe demo.js
8
2

 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服