ES6中类的继承。

通过 extendssuper 继承:通过 class 子类名 extends 父类名 实现继承。

在构造函数 constructor 里面须要写上 super(父类的参数),即在子类中获得父类的this指针。

{
    
    
            //父类
            class Person{
    
    
                name;
                age;
                sex;
                weight;
                height;
                color;
                constructor(n,a,s,w,h,c){
    
    
                    this.name=n;
                    this.age=a;
                    this.sex=s;
                    this.weight=w;
                    this.height=h;
                    this.color=c;
                }
                sleeep(){
    
    }
                eat(){
    
    }
            }
            //子类
            //子类继承父类  必须使用super  代表的是父类的构造
            class Student extends Person{
    
    
                constructor(n,a,s,w,h,c){
    
    
                    super(n,a,s,w,h,c);
                }
            }

            let stu=new Student('小明',18,'男',70,180,'黄色');
            console.log(stu);//小明 18 男 70 180 黄色
        }

        //继承里面的super关键字  可以当函数使用  也可以当对象使用  
        {
    
    
            class A{
    
    
                constructor (){
    
    

                }
                job(){
    
    
                    console.log('工作');
                }
                static work(){
    
    
                    console.log('work 公告');
                }   
            }
            class B extends A{
    
    
                constructor (){
    
    
                    super();
                }
                toString(){
    
    
                    //执行父类的方法
                    //super this
                    super.job();
                    //super  点静态字段不行
                }
            }

            let b=new B();
            console.log(b);
            b.toString();
            B.work();


            console.log(B.__proto__===A);//true
            console.log(B.prototype.__proto__===A.prototype)


        }

猜你喜欢

转载自blog.csdn.net/weixin_46953330/article/details/119296109