ECMAscript6快速入门-Class

class基本

es5>>>

const Hongtao = function(a,b){
    this.a = a;
    this.b = b;
    return this;
}

Hongtao.prototype = {
 constructor : Hongtao,
 print : function(){
     console.log(this.a+' '+this.b);
 }
}

const hongtao = new Hongta('hello','world').print();

es6中>>>

class Hongtao{
    constructor(a,b){
        this.a = a;
        this.b = b;
    }
    print(){
        console.log(this.a + ' ' + this.b);
    }
}

console.log( new Hongtao('hello','world').print() );

class继承

三个关键子字 : extends/static/super

  • extends
    es5中的继承
    //定义一个继承函数
class Parent{
    constructor(name,age){
        this.name = name;
        this.age = age;
    }
    getAge(){
        return this.age;
    }
}
class Sun extends Parent{
    constructor(name,age){
        super(name.age);//需要注意,相当于继承了父类的构造函数中的属性,想继承哪个属性就传哪个参数
    }
    getAge2(){
        return (this.age + 31);
    }
}
class Sun2 extends Sun{
    constructor(name,age){
        super(name,age);//需要注意,相当于继承了父类的构造函数中的属性,想继承哪个属性就传哪个参数
    }
}

console.log(  new Sun('hongtao',21).getAge()  )
console.log(  new Sun2('hongtao',21).getAge2()  )
console.log(  new Sun2('hongtao',21).getAge()  )
  • static
    类相当于实例的原型, 所有在类中定义的方法, 都会被实例继承。 如果在一个方法前, 加上static关键字, 就表示该方法不会被实例继承, 而是直接通过类来调用, 这就称为“ 静态方法”。
class Parent{
    constructor(name,age){
        this.name = name;
        this.age = age;
    }
    static getAge(obj){
        return obj.age;
    }
}
var hong = new Parent('hongtao',21);
console.log( hong.getAge() )//找不到这个方法
console.log( Parent.getAge(hong) )//21
  • super
    ES6中super用于类继承,有二种方式:
    直接作函数使用,但只能用在构造函数中
    作为父类,可调用父类的方法和属性(包括静态)
class Parent{
    constructor(name,age){
        this.name = name;
        this.age = age;
    }
    static getAge(){
        return this.age;
    }
}
class Sun extends Parent{
    constructor(name,age){
        super(name,age);
        this.getAge = Sun.getAge;//构造函数内使用了super,子类会继承父类的静态方法,但只限于构造函数内
    }
    getAge2(){
        return (this.age + 31);
    }
}

PS : 本人也是新手,如有技术问题,请联系QQ : 836717428

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值