• 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
    }
  • 相关阅读:
    设置lable内容不上下居中
    iOS中webView加载URL需要处理特殊字符
    搞一个app需要多久?
    戏说HTML5
    限制UITextField/UITextView的输入字数与中文输入之后的英文换行问题
    iOS6以后的单个控制器横竖屏显示以及旋转屏控制技巧,附带iOS8以后显示电池状态栏
    纯命令行教你Cocoapods的安装和使用
    iOS开发之各种动画各种页面切面效果
    UITextView/UITextField检测并过滤Emoji表情符号
    类里面的大括号{}加载顺序
  • 原文地址:https://www.cnblogs.com/sunyaaa/p/7683686.html
Copyright © 2020-2023  润新知