1. ES6之前的继承方式
// 原来的继承
function Amimal(type,name,age,sex){
this.type = type;
this.name = name;
this.age = age;
this.sex = sex;
}
Amimal.prototype.print = function(){
console.log(`种类:${this.type}`)
console.log(`名字:${this.name}`)
console.log(`年龄:${this.age}`);
console.log(`性别:${this.sex}`)
}
// 子类Dog
function Dog(name,age,sex){
// 只是借助父类的构造函数,当前只是引用不能构成原型链
Amimal.call(this,"犬类",name,age,sex)
}
//构成原型链
Object.setPrototypeOf(Dog.prototype,Amimal.prototype)//设置某个对象的隐式原型 ES5
const d = new Dog("旺财",5,"公")
console.log(d) // {type: "犬类", name: "旺财", age: 5, sex: "公"}
d.print() // 种类:犬类
// 名字:旺财
// 年龄:5
// 性别:公
2. ES6 继承
关键字:extends 继承
super
1. 直接当成函数使用,表示调用父类的构造器
2. 当成对象使用,表示父类的原型
class Amimal {
constructor(type,name,age,sex){
this.type = type;
this.name = name;
this.age = age;
this.sex = sex;
}
print(){
console.log(`种类:${this.type}`)
console.log(`名字:${this.name}`)
console.log(`年龄:${this.age}`);
console.log(`性别:${this.sex}`)
}
}
class Dog extends Amimal{
// 如果定义了constructor 表示当前对象时子类,
// 则必须在constrcutor第一行手动调用父类的构造函数,否则会报错
constructor(name,age,sex,loves){
super("犬类",name,age,sex)
this.loves = loves;
}
// 如果说子类不写constructor,则会有默认的构造器,自动去调用父类的构造器
print(){//子类和父类有同名的方法,先用自己的
super.print()//2
console.log(`爱好:${this.loves}`)
}
}
const d = new Dog("旺财",5,"公","吃骨头")
console.log(d)
d.print()