ES6继承涉及到多个变量如何解决?

'use strict';

class Person {
    // 构造函数,实例化的时候将会被调用,如果不指定,那么会有一个不带参数的默认构造函数.
    constructor(name) {
        this.name = name;
    }

    // printout 是原型对象上的方法(函数)
    personPrintOut() {
        console.log('name:' + this.name);
    }
}
// console.log(Animal('A',50));//ERROR Class constructor Animal cannot be invoked without 'new'
var A = new Person('A');
A.personPrintOut();

// 继承
class People extends Person {
    constructor(name, age) { //构造函数
        super(name);    //调用父类构造函数
        this.age = age;
    }

    peoplePrintOut() {
        console.log('name:' + this.name + ',age:' + this.age);
    }
}
var B = new People('B', 20);
B.peoplePrintOut();

//继承
class human extends People {
    constructor(name, age, height) { //构造函数
        super(name, age);    //调用父类构造函数
        this.height = height;
    }

    humanPrintOut() {
        console.log('name:' + this.name + ',age:' + this.age + ',height:' + this.height);
    }
}
var C = new human('c', 20, 200);
C.humanPrintOut();

如果现在我需要建立一个D extends C;constructor里面的变量(name, age, height)难道都要一个一个的写出来然后给super传参吗?

阅读 3.1k
1 个回答

rest参数 + 解析构

constructor(...args) {
    super(...args);
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题