您现在的位置:首页 >> 前端 >> 内容

es6class类

时间:2017/9/13 10:33:00 点击:

  核心提示:class类classPerson{constructor(name,age,job){this.name=name;this.age=age;this.job=job;this.friends=[S...

class类

classPerson{

constructor(name,age,job){

this.name=name;

this.age=age;

this.job=job;

this.friends=['Shelby','Court'];

}

sayName(){

console.log(this.name);

}

}

letperson=newPerson('张三',26,'司机');

person.sayName();

2.静态方法:

classPoint{

constructor(x,y){

this.x=x;

this.y=y;

}

staticdistance(a,b){

constdx=a.x-b.x;

constdy=a.y-b.y;

returnMath.sqrt(dx*dx+dy*dy);

}

}

constp1=newPoint(5,5);

constp2=newPoint(10,10);

console.log(Point.distance(p1,p2));

3.ES6明确规定,Class内部只有静态方法,没有静态属性,但可以用另外方式解决

classFoo{

}

Foo.prop=1;

Foo.prop//1

//---单例模式

classCache{

staticgetInstance(){

if(!Cache.instance){

Cache.instance=newCache();

}

returnCache.instance;

}

}

varcache=Cache.getInstance();

4.继承:

classAnimal{

constructor(name){

this.name=name;

}

speak(){

console.log(this.name+'makesanoise.');

}

}

classDogextendsAnimal{

speak(){

console.log(this.name+'barks.');

}

}

letdog=newDog('旺财');

dog.speak();

//-------------------vue中loginbean的单例模式--------------------------

classLoginBean{

staticgetInstance(){

if(!LoginBean.instance){

LoginBean.instance=newLoginBean();

}

returnLoginBean.instance;

}

constructor(){

this.id=0;

this.nicheng=null;

}

}

varloginbean=LoginBean.getInstance();

exportdefaultloginbean;

 

Tags:ES S6 6C CL 
作者:网络 来源:easyClub_h