继承:获取存在对象已有属性和方法的一种方式
继承的目的:重复使用代码,提高重用性
原型继承
function Parent(name) {
this.name = name
}
Parent.prototype.sayName = function (){
console.log(this.name)
}
function Child(name, age) {
Parent.call(this, name)//将Parent的this指向Child的this对象上
this.age = age
}
Child.prototype = Object.create(Parent.prototype)//做对象的原型继承
Child.prototype.constructor = Child //修正constructor 指向
Child.prototype.sayAge = function (){
console.log(this.age)
}
let c1 = new Child('哈哈',18)
c1.sayAge()// 18
c1.sayName()// 哈哈
class 继承
extends:Class可以通过extends关键字实现继承
super :super关键字既可以当作函数使用,也可以当作对象使用。 super 作为函数调用时表示父类的构造函数,用来新建父类的this对象
super注意事项:
- 子类必须在 constructor 方法中调用 super 方法,否则新建实例时会报错
- 在子类的构造函数中,只有调用super之后,才能使用this关键字,否则会报错
- 子类没有定义 constructor 方法,那么这个方法就会被默认添加
- super 虽然代表了父类的构造函数,但是返回的是子类的实例
- 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调用父类的构造函数
// super必须在子类this之前调用
super(x,y)
this.x = x
this.y = y
}
subtract(){
console.log(this.x - this.y)
}
}
let son = new Son(10,5)
son.sum()//15
son.subtract()//5
super作为对象时,在普通方法中,指向父类的原型对象
class A {
p() {
return 2;
}
}
class B extends A {
constructor() {
super();
console.log(super.p()); // super当作一个对象使用
}
}
let b = new B();