javascript - ES6继承涉及到多个变量如何解决?
怪我咯
怪我咯 2017-04-11 11:46:11
[JavaScript讨论组]
'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传参吗?

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(1)
高洛峰

rest参数 + 解析构

constructor(...args) {
    super(...args);
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号