ES6-class

javascript的语言传统方法是通过构造函数,定义并生成新的对象:

function point(x,y){

 this.x = x;

this.y = y;

}

point.prototype.toString = function(){

  return '('+this.x+this.y+')'

}

var  p =  new point(1,2);

p.toString();// (1,2)

es6提供了更接近传统语言的写法,引入了class(类)的概念,作为对象的模板。上面的代码用es6可以改写成如下方式:

class point {

constructor (x,y) {//构造方法

//该方法是类默认的方法,如果没有显示的声明,一个空的构造方法也会被默认添加的。

   this.x = x;

   this.y = y;

}

toString () {

return '('+this.x+this.y+')'

}

toValue(){

}

}

point类除了构造方法,还定义了一个toString方法。注意,定义“类”的方法的时候,前面不需要加上function这个关键字,直接把函数定义放进去了就可以了。另外,方法之间不需要逗号分隔,加了会报错。

类的数据类型就是函数,类本身就是指向构造函数。

使用的时候,也是直接对类使用new命令,跟构造函数完全一致。

var m =new point(1,2);

m.toString();//(1,2)

构造函数的prototype属性,在es6的类上面继续存在。事实上类的所有方法都定义在这个属性上面。

point.prototype = {

   toString(){},

   toValue(){}

}

在类的实例上调用,就是调用原型上的方法。

class B{}

let b = new B();

b.constructor === b.prototype.constructor //true

由于类的方法都定义在prototype对象上面,所有类的新方法的添加都可以通过这个对象添加。Object.assign方法可以很方便的一次向类添加多个方法。

class Point {


}

Object.assign(Point.prototype,{

toString(){},

toValue(){}

});

prototype对象的construcor属性,直接指向类本身,另外,类内部定义的方法是不可以枚举的,在es5中是可以枚举的。

与es5一样,实例的属性除非显示的定义在其本身(通过this),否则都是定义在原型上的,即在class上面

//定义类                                                                  classPoint{constructor(x,y){this.x=x;this.y=y;}toString(){return'('+this.x+', '+this.y+')';}}


var point=newPoint(2,3);


point.toString()// (2, 3)


point.hasOwnProperty('x')// true


point.hasOwnProperty('y')// true


point.hasOwnProperty('toString')// false


point.__proto__.hasOwnProperty('toString')// true

class 不存在变量的提升 必须保证先声明在前调用在后,子类必须在父类的后面 

let Foo = class {}

class Bar extends Foo{//类的继承

}


类的继承 extends

class ColorPoint extends Point {

  constructor(x,y,color){

   super(x,y);//调用父类的构造函数

   this.color = color;

  }

toString () {

return this.color+''+super.toString()//调用父级的方法

}

}

上面代码中,constructor方法和toString方法之中,都出现了super关键字,它在这里表示父类的构造函数,用来新建父类的this对象。子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。





你可能感兴趣的:(ES6-class)