zoukankan      html  css  js  c++  java
  • ES6新特性使用小结(五)

    十二、class 与 extends

     ①、类的基本定义和生成实例

    {   
        class Parent{
            constructor(name='Lain'){          //定义构造函数
                this.name = name;
            }
        }
        let a = new Parent('Mayu');   //生成实例
        console.log(a);             //Parent {name: "Mayu"}
    
        //继承
        class Child extends Parent{         //通过 关键字 extends    实现继承
    
        }
        let b = new Child();
        console.log(b)      //Child {name: "Lain"}      继承了Parent 并使用了Parent的默认值
    }

    ②、通过 extends 实现继承

    {
        class Parent{
            constructor(name='Lain'){
                this.name = name;
            }
        }
        //继承
        class Child extends Parent{         //通过 关键字 extends    实现继承
            constructor(name='child'){      //定义了子类的默认值
                super(name);                //使用 super方法传递参数
                this.type='child';          //      **在继承关系中 如果使用了super 一定要将 super方法放在第一行
            }
        }
        let b = new Child();
        console.log(b)      //Child {name: "child", type: "child"}      继承了Parent 并使用了Child的默认值
    }

    ③、class 中的 getter 和 setter

    {   
        class Parent{
            constructor(name='Lain'){
                this.name = name;
            }
            get longName(){         //  ** 这里是属性 而不是方法
                return  'Hello '+this.name;
            }
            set longName(value){
                this.name =value;
            }
        }
    
        let c = new Parent();
        console.log('getter',c.longName);   //getter    Hello Lain
        c.longName = 'abc';
        console.log('setter',c.longName);     //setter Hello abc
    }

    ④、class 中的 静态方法

    {   
        class Parent{
            constructor(name='Lain'){
                this.name = name;
            }
    
            static tell(){          //  使用 关键字 static 定义静态方法
                                    //  ***  该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。
                console.log('static');
            }
        }
        Parent.tell();      //static
    }

    ⑤、class 中的 静态属性

    {   
        class Parent{
            constructor(name='Lain'){
                this.name = name;
            }
    
            static tell(){
                console.log('static');
            }
        }
        Parent.type  ='test';           // 在 class 定义完毕后 在 类 上直接定义 静态方法 而不是在实例上
        console.log('静态属性',Parent.type);        //静态属性 test
    }
  • 相关阅读:
    一些小姿势
    <学习笔记>《具体数学》
    【react】报错Need at least a key or a value or a label (only for OptGroup) for [object Object]
    Calibration Checkerboard Collection
    华为云如何建表并创建作业定时调度抽取数据
    HIVE SQL教程
    postgresql 教程
    PC机启用了fiddler代理,在手机或其它机器上连接该代理,无法抓包
    Unity3d的Scroll View组件不能滑动到底的解决方式
    Unity3d让GridLayoutGroup按照子物体的数量自动调整宽高
  • 原文地址:https://www.cnblogs.com/sunyaaa/p/7683686.html
Copyright © 2011-2022 走看看