JavaScript、ES6中的类的继承

类的继承
extends  connstructor  super
例1:
       class Father {
            constructor(){}
            money(){
                console.log("10000块");
            }
        }
        // 子类Son使用 extends 继承父类Father
        class Son extends Father {}
        var ss = new Father();
        ss.money();
        // 10000块

例2:

        class Fa {
            constructor(x, y){
                this.x = x;
                this.y = y;
            }
            sum(){
                var su = this.x + this.y;
                console.log(su);
            }
        }
        class Son extends Fa{
            constructor(x, y){ // constructor用于存放类的共有属性
                this.x = x;
                this.y = y;
            }
        }
        var son = new Son(1, 2);
        son.sum();
        // 输出:Uncaught ReferenceError: Must call super constructor in derived 
class before accessing 'this' or returning from derived constructor

原因:

    实例对象son中的参数(1,2)其实是指向子类Son中的constructor(x,y) 并非 父类Fa中的constructor(x,y) 所以无法使用sum()方法。

改进:

   super关键字 用于访问和调用父类上的构造函数。可以调用父类的构造函数,也可以调用父类的普通函数
        class Fa {
            constructor(x, y){
                this.x = x;
                this.y = y;
            }
            sum(){
                var su = this.x + this.y;
                console.log(su);
            }
        }
        class Son extends Fa{
            constructor(x, y){ 
                super(x, y);// 调用了父类的构造函数constructor
            }
        }
        var son = new Son(1, 2);
        son.sum();
        // 3

  

 

猜你喜欢

转载自www.cnblogs.com/sylys/p/11652747.html