面向对象2
继承与多态
//extends继承关键词
class Person{
constructor(){ //构造函数
this.name = "张三"
this.eat = function(){
console.log('吃饭');
}
}
}
class Student extends Person{
constructor(){ //使用Student来继承Person, 获取父类一切的非私有的方法和属性
super() //在子类的构造器中如果要使用this关键词 必须要写super()
this.age = 18
//重写this.eat 本身继承于父类的方法,现在在这里面重写了这个方法
this.eat = function(){
console.log('吃米饭');
}
}
}
let student = new Student()
console.log(student.age);//访问自己的age属性
console.log(student.name);//父类的name属性,现在属性student,继承于父类
student.eat()
//继承最大的好处就是减少了代码的冗余
//重写是多态的特性(一个物质的多种形态 子类是父类形态的体现)
//多态在java语言的运用:通过子类来创建一个父类 重写是子类重写父类的方法 重载是在一个类里面有多个参数
class a{
constructor(liList,spans,pre,next){
this.liList = liList
this.spans = spans
this.pre = pre
this.next = next
this.autoMove = function(){
//liList里面left值改变
//spans里面样式改变
}
}
}
class b extends a{
constructor(liList,spans,pre,next){
super(liList,spans,null,null)//指向父类的构造方法
this.autoMove = function(){//重写方法
//liList里面top值改变
//spans里面样式改变
}
}
}