js笔记八:class

一、说明

在es6中增加了一个class,简单明了,比ES5下面强多了
每个类都有会有一个构造函数constructor。如果没有申明,则会默认分配一个空的。
如果需要调父类的构造函数,需要在constructor第一行调用super,至于为什么,已经有N多文档说明了。
例如:

class a {
    constructor(m) {
        this.m_m = m;
    }
};
class b extends a {
    constructor(m, m1) {
        super(m);
        this.m_m1 = m1;
    }
};

二、属性方法

在es6中,使用get和set来标明属的读写函数

class a {
    constructor(m) {
        this.m_m = m;
    }
    get m() { return this.m_m; }
    set m(v) { this.m_m = v; }
};
let testa = new a(1999);
console.log(testa.m);

在这里就会 打印出1999

三、非静态成员函数

class a {
    constructor(m) {
        this.m_m = m;
    }
    get m() { return this.m_m; }
    set m(v) { this.m_m = v; }
    mult(k) {
        return this.m_m * k;
    }
    add(k) {
        return this.m_m + k;
    }
    sub(k) {
        return this.m_m / k;
    }
};

在这里可以看到,不需要用function了,又是做了大大的简化。

四、静态成员函数

只需要在类的成员方法前,加一个static关键字就可以了,如果同一个类的静态函数,可以用this来调用。如下面的astatcfun1调用astatcfun,也可以用类名.的方问,如astatcfun2调用astatcfun,建议还是用this,在使用的时候,静态方法,不需new出对象来,直接用对象.的方式,如下面的testcall调用a的静态方法。也可以派生给子类。

class a {
    constructor(m) {
        this.m_m = m;
    }
    static astaticfun() {
        return 100;
    }
    static astatcfun1() {
        return this.astaticfun() + 200;
    }
    static astatcfun2() {
        return a.astaticfun() + 200;
    }


    get m() { return this.m_m; }
    set m(v) { this.m_m = v; }
    mult(k) {
        return this.m_m * k;
    }
    add(k) {
        return this.m_m + k;
    }
    sub(k) {
        return this.m_m / k;
    }
};
//
function testcall(){

    console.log(a.astaticfun());

    console.log(a.astatcfun1());

    console.log(a.astatcfun2());
}

静态成员函数的调用

class a {
static aaa() {
return "aaa";
}
static bbb() {
return this.aaa() + "bbb";  //同一个类的静态函数调用函数,只需要用this.就可以
}
kkk() {
return "kkk";
}
ccc() {
return a.aaa() + "ccc" + this.kkk(); //同一个类的非静态函数调用静态函数,则需要类名.的方式
}
};
let c = new a();

console.log(a.bbb());
console.log(c.ccc());

五、派生

在ES6的派生通过extends这个关键字就可以,如

class b extends a() {
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值