程序中的继承: 子类可以继承父类的一些属性和方法
class Father { //父类
constructor () {
}
money () {
console.log(100)
}
}
class Son extends Father { //子类继承父类
}
let son = new Son()
son.money() // 100
son.
super关键字用于访问和调用对象父类上的函数,可以通过调用父类的构造函数,也可以调用父类的普通函数
class Father { //父类
constructor (x, y) {
this.x = x
this.y = y
}
money () {
console.log(100)
}
sum () {
console.log(this.x + this.y)
}
}
class Son extends Father { //子类继承父类
constructor (x, y) {
super(x, y) //调用了父类中的构造函数
}
}
let son = new Son(1,2)
son.sum() // 3
son.
继承的特点:
class Father {
say() {
return '我是父元素'
}
sing() {
return '父元素唱一首歌'
}
}
class Son extends Father {
say() {
console.log('我是子元素')
}
sing() {
console.log(super.sing())
}
}
var son = new Son()
son.say() //我是子元素
son.sing() //
子元素可以继承父元素的方法的同时,子元素也可以扩展自己的其他方法,子类在构造函数中用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 调用父类的构造函数
super(x,y)
this.x = x
this.y = y
}
subtract() {
console.log(this.x - this.y)
}
}
let son = new Son(5,3)
son.subtract() // 2
son.sum() //8
constructor里面的this指向实例对象,方法里面的this向这个方法的调用者
这篇文章主要分享了,关于类的继承、继承需要的用到的extends,super、ES6中的类和对象的注意点等。
如果想了解更多,请扫描二维码
原文:https://www.cnblogs.com/lfcss/p/12375217.html