张蕾的技术博客Web前端之路让前端飞

es6解读4:类

2017-07-16  本文已影响245人  cd72c1240b33

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

class Parent{
    constructor(name='leilei'){
        this.name=name;
    }
}
let v_parent=new Parent('ymy');
console.log(v_parent.name)

类的继承: extends

class Parent{
    constructor(name='leilei'){
        this.name=name;
    }
}
class Child extends Parent{
    //继承:子类怎么在自己的构造函数中传递参数
    constructor(name='child'){
        super(name);//如果不传参,子类使用的是父类默认的参数;super一定放在构造函数的第一行;
        this.type='child';
    }
}
console.dir(new Child('hello'))

类中的getter和setter

class Parent{
    constructor(name='leilei'){
        this.name=name;
    }
    get longName(){
        return 'ymy '+this.name;
    }
    set longName(value){
        this.name=value;
    }
}
// 创建实例
let p1=new Parent();
console.log(p1.longName) //获取属性
p1.longName='tangtang'; //设置属性

给类中添加静态方法 static

class Parent{
    constructor(name='leilei'){
        this.name=name;
    }
    //设置静态方法
    static tell(){
        console.log('tell');
    }
}
Parent.sex='gril';  //设置类的静态属性
Parent.tell() //调用类的静态方法;
上一篇 下一篇

猜你喜欢

热点阅读