es6总结

es6定义类

class Point {

  constructor(x,y){

    this.x = x;

    this.y = y;

  }

  toString() {

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

  }

}

1、构造函数的this指向的是实例对象

创造一个实例对象

var point = new Point()

point.toString()

在类的实例上面调用方法,其实就是调用原型上的方法,即类的方法都是定义在prototype对象上面的,可以通过Object.assign方法很方便的一次向类添加多个方法

Object.assign(point.prototype,{toString(){},toValue(){}})

类的内部所有定义的方法,都是不可枚举的,这与es5有区别

2、严格模式

类和模块内部,默认的就是严格模式

3、不存在变量提升

4、this的指向

类的方法内部如果含有this,它默认指向类的实例,但是一旦单独使用该方法,很可能报错

一个比较简单的方法就是在构造函数中绑定this,

constructor(){

  this.printName = this.printName.bind(this)

}

另一种方法就是使用箭头函数

this.printName = (name='name')=>{

  this.print(`hello ${name}`);

}

5、class的静态方法

所有类中定义的方法,都会被实例继承,static 静态方法,不能被实例继承

class Foo{

  static classMethod(){

  return 'hello';

  }

}

classMethod()可以直接在Foo类上调用,如果在实例上调用静态方法,会抛出错误

如果静态方法包含this关键字,这个this指的是类,而不是实例 

父类的静态方法,可以被之类继承

原文地址:https://www.cnblogs.com/liangshuang/p/8507751.html