继承的使用
继承
子类继承父类 可以拥有父类的方法及属性 这个称为继承
继承的使用
1.使用extends来实现继承(es6的class)
// 继承 class类 的继承 extends继承关键词
class Person{
constructor(){ //构造函数
this.name = '张三'
this.eat = function(){
console.log('干饭');
}
}
}
class Student extends Person{ //使用student来继承Person 获取父类一切的非私有的方法和属性
constructor(){
super() //在子类的构造器中如果要使用this关键词 必须先写super()
this.age = 18
// 重写 this.eat 本身继承于父类的方法 现在在这里面我重写了这个方法
this.eat = function(){
console.log('喝西北风')
}
}
}
let student = new Student()
console.log(student.age); //访问自己的age属性 18
console.log(student.name); //父类的name属性 这个name属性现在属于student对象 他继承于Person的属性 张三
2.使用原型继承
function Person(){ //构造函数
this.name = '王五'
}
function Teacher(){//构造函数
this.age = 80
}
Teacher.prototype = new Person()
let teacher = new Teacher()
console.log(teach.name)//王五
继承的层次
class a{
constructor(){ //构造函数
this.name = '张三'
this.age = 18
this.sex = '男'
}
}
class b extends a{
constructor(){ //构造函数
super()
this.name = '张三'
this.addr = '湖南长沙'
}
}
class c extends b{
constructor(){ //构造函数
super()
this.name = '李四'
}
}
console.log(new c().name) //李四
console.log(new c().age) //18 b里面的18
console.log(new c().sex) //男 b里面的男
console.log(new c().addr) //湖南长沙 b里面的地址
b 继承 a c 继承 b c是否继承a (c是a的子类 c没有直接继承a)