啥是类的继承
如果两个类Animal和Dog,如果可以描述为:**Dog是 Animal,则,Animal和Dog**形成继承关系
如果**Dog是Animal**,则可以叫做:
1.** Dog继承自**Animal
2.** Animal派生**Dog
3.** Dog是Animal的子类
4. Animal是Dog**的父类
如果**Animal是Dog的父类,则Dog会自动拥有Animal**中的所有实例成员。
如何实现的类的继承
es5实现继承前
让Dog 继承与 Animal
function Animal(type, name, age, sex) {this.type = type;this.name = name;this.age = age;this.sex = sex;}Animal.prototype.print = function () {console.log(`【种类】:${this.type}`);console.log(`【名字】:${this.name}`);console.log(`【年龄】:${this.age}`);console.log(`【性别】:${this.sex}`);}function Dog(name, age, sex) {}const dog = new Dog('旺财',3,'公')console.log(dog)
他们的原型链如图
想要实现Dog继承Animal那吗Dog的prototype的proto就得指向animal的prototype如下图
代码如下
function Animal(type, name, age, sex) {this.type = type;this.name = name;this.age = age;this.sex = sex;}Animal.prototype.print = function () {console.log(`【种类】:${this.type}`);console.log(`【名字】:${this.name}`);console.log(`【年龄】:${this.age}`);console.log(`【性别】:${this.sex}`);}function Dog(name, age, sex) {//借用父类的构造函数Animal.call(this, "犬类", name, age, sex);}// 将Dog的_proto指向Animal的prototypeObject.setPrototypeOf(Dog.prototype, Animal.prototype);const d = new Dog("旺财", 3, "公");d.print();console.log(d);
但这是es5中的写法
在其es6中的写法为
关键字
extends :**继承,用于类的定义
super:
直接当函数调用,表示父类构造函数
如果当做对象使用,则表示父类的原型
es6要求如果定义了constructor,并且该类是子类,则必须在constructor的第一行手动调用父类的构造函数
如果子类不写co**nstructor,则会有默认的构造器,该构造器需要的参数和父类一致,并且自动调用父类构造器
class Animal {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}`);}jiao(){throw new Error("动物怎么叫的?");}}// 使用extends 关键字 让其Dog 继承与Animalclass Dog extends Animal {constructor(name, age, sex) {//此处当做函数调用,但是supper()必须写在constructor里的第一行,让先调用一次才能实现类的继承。否则无法super("犬类", name, age, sex);// 子类特有的属性this.loves = "吃骨头";}print(){//调用父类的print//此处supper被当做对象调用,此处supper就表示父类的prototypesuper.print();//自己特有的代码console.log(`【爱好】:${this.loves}`);}//同名方法,会覆盖父类jiao(){console.log("旺旺!");}}const d = new Dog("旺财", 3, "公");d.print();console.log(d)d.jiao();
