首页 > 其他 > 详细

ES6中的类

时间:2019-09-21 20:29:24      阅读:83      评论:0      收藏:0      [点我收藏+]

类的基本定义和生成实例:

    class Parent{
        //定义构造函数 constructor 方法
        constructor(name=‘课程‘){
            this.name = name;
        }
    }
    //生成实例
    let parent1 = new Parent(‘慕课网‘);
    console.log(parent1)//Parent {name: "慕课网"}

 继承:

    class Parent{
        //定义构造函数 constructor 方法
        constructor(name=‘旺财‘,sex = ‘男‘){
            this.name = name;
            this.sex = sex;
        }
    }
    console.log(new Parent())//Parent {name: "旺财", sex: "男"}
    class Child extends Parent{
        constructor(name = ‘如花‘,sex=‘女‘,age = 15){
            super(name)//指定子类的默认参数不沿用父类的默认参数 若为空则所有默认参数都沿用父类的默认参数
            this.age = age;
        }
    }
    console.log(new Child())//Child {name: "child", sex: "男", age: 15}
    console.log(new Child(‘小强‘,undefined,18))//Child {name: "小强", sex: "男", age: 18}

 get和set的基本用法:

    class Parent{
        //定义构造函数 constructor 方法
        constructor(name=‘旺财‘,sex = ‘男‘){
            this.name = name;
            this.sex = sex;
        }
        get longName(){
            return this.name
        }
        set longName(value){
            this.name = value;
        }
    }
    let v = new Parent();
    console.log(v.longName)//旺财
    v.longName = ‘小强‘;
    console.log(v.longName)//小强

类的静态方法: 

    class Parent{
        constructor(name=‘mukewang‘){
            this.name=name;
        }
        static tell(){  // 静态方法  关键字static
            console.log(‘tell‘);
        }
    }
    Parent.tell(); // tell      由类直接调用静态方法

静态属性: 

    class Parent{
        constructor(name=‘mukewang‘){
            this.name=name;
        }
        static tell(){
            console.log(‘tell‘);
        }
    }
    Parent.type=‘test‘;//直接定义静态属性
    console.log(‘静态属性‘,Parent.type); //静态属性 test

ES6中的类

原文:https://www.cnblogs.com/rickyctbur/p/11564327.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!