es6之class(类)用法

ES6 类(class)

js语言的传统方式是通过定义构造函数,生成心得对象。是一种基于原型的面向对象系统。在es6中增加了class类的概念,可以使用class关键字来声明一个类。之后用这个类来实例化对象。

构造函数示例

const Demo = function(a,b){
  this.a = a;
  this.b = b;
  return this;
}

Demo.prototype = {
  constructor: Demo,
  print: function(){
    console.log(this.a+this.b);
  }
}

const demo = new Demo('jane','yun').print();
class Demo {
  constructor(a,b){
     this.a = a;
     this.b = b;
     return this;
  }
  print(){
    console.log(this.a+this.b);
  }
}

const demo = new Demo('hello','world').print();

Demo中的constructor是构造方法,this关键字代表示例对象。

注:定义类的方法的时候不需要写function,另外 也不需要逗号。

2:静态方法

class Point{
  constructor(a,b){
    this.a = a;
    this.b = b;
    return this;
  }
  static print(){
     console.log('say hi');
  }
}

const Point.print();

3:继承

class A{
  constructor(a){
    this.a = a;
    return this;
  }
  string(){
    return 'hello,'+ this.a
  }
}

class B extends A{
   constructor(a){
     super();
   }
   m(){
     super.sting();
   }
}

const b = new B(3);
super
  1、super作为函数调用时,代表父类的构造函数。ES6 要求,子类的构造函数必须执行一次super函数。
  2、super作为对象时,在普通方法中,指向父类的原型对象;在静态方法中,指向父类
  super代表了父类A的构造函数,但是返回的是子类B的实例,即super内部的this指的是B,因此super()在这里相当于A.prototype.constructor.call(this)。
posted @ 2018-06-20 16:53  二月花开  阅读(2814)  评论(0编辑  收藏  举报