1.class继承的实现
2.super关键字
3.方法的重写
<script>
//es5
function Animal(name,color){
this.name = name;
this.color = color;
}
Animal.prototype.eat = function(){
console.log(this.name + "is eating" ); //兔八哥is eating
}
Animal.prototype.sleep = function(){
console.log(this.name + "is sleeping"); //兔八哥is sleeping
}
//继承
function Rabbit(name,age,color){
//调用父类构造函数
Animal.apply(this,arguments);
this.age = age;
}
//通过原型传递
function foo(){};
foo.prototype = Animal.prototype;
Rabbit.prototype = new foo();
Rabbit.prototype.constructor = Rabbit;
let rabbit = new Rabbit("兔八哥","white",10);
rabbit.eat();
rabbit.sleep();
console.log(rabbit); //Rabbit {name: "兔八哥", color: "white", age: "white"}
//es6:更简洁、直观
class Animal{
constructor(name,color){
this.name = name;
this.color = color;
}
eat(){
console.log(this.name + "is eating" ); //兔八哥is sleep
}
sleep(){
console.log(this.name +"is sleep"); //兔八哥is eating
}
}
class Rabbit extends Animal{
constructor(name,color,age){
//子类中通过super调用父类的构造函数,一定要放在第一行
// super访问父类的方法
super(name,color);
this.age = age;
}
//子类通过定义同名的方法覆盖父类中的方法,当子类对象调用的时候,优先执行子类自己拥有的方法
eat(){
console.log("露出了常常的牙齿") // 露出了常常的牙齿
}
test(){
//通过super关键字,调用父类对象中的方法
super.eat();
}
}
let rab = new Rabbit("兔八哥","白色",10);
rab.eat();
rab.sleep();
rab.test();
console.log(rab); //Rabbit {name: "兔八哥", color: "白色", age: 10}
</script>
《待更新》