es6声明一个类

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)。
 
分类: javascript
原文地址:https://www.cnblogs.com/xzybk/p/12540184.html