一、说明
在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() {
};