ES6面向对象

作者: 番茄向前看 | 来源:发表于2020-03-15 19:57 被阅读0次

    类声明与构造函数

    class 声明类
    constructor 构造函数

        <script>
            class Person {
                constructor(name, age) {
                    this.name = name;
                    this.age = age;
                }
                //方法
                showPerson() {
                    console.log(this.name, this.age);
                }
            }
            //实例化
            let person = new Person("番茄向前看", "18");
            person.showPerson();//调用类方法
        </script>
    

    继承与超类

        <script>
            //定义父类
            class Person {
                constructor(name, age) {
                    this.name = name;
                    this.age = age;
                }
                //方法
                showPerson() {
                    console.log(this.name, this.age);
                }
            }
            //子类的继承
            class Worker extends Person {
                constructor(name, age, job) {
                    super(name, age);//可以使用super(超类)继承属性
                    this.job = job;
                }
                //方法
                showJob() {
                    console.log(this.job);
                }
            }
            //实例化子类
            let workers = new Worker("石头", "15", "没有工作")
            //调用子类方法
            workers.showJob()
            //调用父类方法
            workers.showPerson()
        </script>
    

    相关文章

      网友评论

        本文标题:ES6面向对象

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