美文网首页
extends和super

extends和super

作者: ticktackkk | 来源:发表于2020-06-01 15:45 被阅读0次

一、extends和super

      class Father {
            constructor(x, y) {
                this.x = x;
                this.y = y;
            }
            sum() {
                console.log(this.x + this.y);
            }
        }
        class Son extends Father {
            constructor(x, y) {
                super(x, y)//调用父类中的构造函数,把x,y传给父类
            }
        }
        var son = new Son(1, 2);
        son.sum() //3

1.如果没有super关键字,会报错因为Father中的sum()指向 的是自己的constructor,但是new Son()中是传给了子项的constructor,所以里面的this.x this.y指向的是子类的congstructor,父类是没有得到这两个数值的,所以sum没有办法执行两个数相加。总之sum必须接受父类中constructor中的参数才能相加
2.super关键字:
super关键字可以访问调用父类的函数,可以调用父类的构造函数,也可以调用父类的普通函数
3.顺序为 new Son 把1和2传给了子类的constructor x和y 执行了super ,super调用了父类的constructor通过super把子类的1和2传给父类的constructor,最后父类中的sum()可以使用sonstructor中的两个数据

二、super关键字调用父类函数

   class Father {
            say() {
                return "我是爸爸";
            }
        }
        class Son extends Father {
            say() {
                console.log(super.say() + "的儿子");
                //super.say()就是调用父类中的普通函数say()
            }
        }
        var son = new Son();
        son.say()

就近原则:
1.继承中,先看子类也没有这个方法,如果有就先执行子类的方法
2.继承中,如果子类没有这个方法,就去看父类有没有这个方法,如果有就去执行父类的这个方法

三、super关键字必须在子类this之前调用

   class Father {
            constructor(x, y) {
                this.x = x;
                this.y = y;
            }
            sum() {
                console.log(this.x + this.y);

            }
        }
        class Son extends Father {
            constructor(x, y) {
                //利用super调用父类的构造函数
                //super必须在在子类this之前调用
                super(x,y)
                this.x = x;
                this.y = y;
                
            }
            subtract() {
                console.log(this.x - this.y);
            }
        }
        var son = new Son(5, 3);
        son.subtract();
        son.sum();

相关文章

网友评论

      本文标题:extends和super

      本文链接:https://www.haomeiwen.com/subject/ifcszhtx.html