es6中class实现构造函数的继承

102 阅读1分钟

  //使用class关键字定义一个类型(父类)
    class Father {
      //添加构建函数和属性
      constructor(name, age) {
        this.name = name
        this.age = age
      }
      //添加构建方法:也是将成员添加到原型中(直接添加)
      say() {
        console.log(1);
      }
    }
    let fa = new Father('jack', 20)
    console.log(fa);
    fa.say()

    //extends:实现继承
    //定义一个类 Son 继承自 Father
    //extends:默认可以实现,父类成员的完整继承(构造器,原型中的成员)
    //1.继承父类的构造函数
    //2.继承父类的原型中的所有成员
    class Son extends Father {
      //添加构建函数
      constructor(name, age, gender) {
        //调用父类构造器,构造子类对象的成员
        super(name, age)
        // Must必须 call调用 super超(父) constructor构造函数 in在 derived派生(子) class类 before在...之前 accessing访问 'this'this or或者 returning返回 from从 derived派生 constructor构造函数:在子类构造函数使用this或者reutrn之前,必须调用父类的构造函数
        // this.name = name
        // this.age = age
        this.gender = gender // 添加子类自己的新属性
      }
      code() {
        console.log(2);
      }
    }
    let son = new Son('lf', 22, '男')
    console.log(son);
    son.say()
    son.code()