es6 class类继承(extends、super)

Class 可以通过extends关键字实现继承,这比 ES5 的通过修改原型链实现继承,要清晰和方便很多。

1.extends 继承,用于类中的定义

2.super ①当成函数使用,表示父类的构造器 ②当成对象使用,则表示为父类的原型

它指代父类的实例(即父类的this对象)。子类必须在constructor方法中调用super方法,否则新建实例时会报错。

实例:

 // ES6 class继承
        // 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},名字:${this.name},名字:${this.name},性别:${this.sex}`);
            }
        }
        class Dog extends Amimal{
            //1.如果定义了constrcutor表示当前类是子类,则必须在constrcutor的第一行手动调用父类的构造函数
            //也就是说必须使用super关键字,如果不写就会报错
            constructor(name,age,sex){
                super('犬类',name,age,sex)
                this.hobby = '舔'
                this.say = "汪"
            }
            //2.如果子类不写constructor,则会有默认的构造器去调用父类的构造器
            print(){
                console.log(`爱好:${this.hobby},叫声:${this.say}`);
                super.print()
            }
        }
        const d = new Dog('小黑',4,'公')
        d.print()
        // d.__proto__->Dog.prototype.__proto__ ->Amimal.prototype().__proto__ -> Object

猜你喜欢

转载自blog.csdn.net/A20201130/article/details/123645550