首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【前端】Javascript高级篇-类的继承

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

作者头像
瑞新
发布2020-07-07 18:35:37
3730
发布2020-07-07 18:35:37
举报

继承普通方法

// 父类
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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-05-29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 继承普通方法
  • 继承extend计算
  • super关键字-调用父类函数
    • 调构造函数
      • 调普通函数
        • 方法重写,就近调用
        • 子方法中调父普通函数
        • 继承父类方法同时扩展子类方法
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档