ES6 class 类

类实际上是个“特殊的函数”,就像你能够定义的函数表达式函数声明一样,类语法有两个组成部分:类表达式类声明

类声明

class Rectangle {
 constructor(height, width) {
   this.height = height;
   this.width = width;
}
}

类表达式

/* 匿名类 */ 
let Rectangle = class {
 constructor(height, width) {
   this.height = height;
   this.width = width;
}
};

/* 命名的类 */
let Rectangle = class Rectangle {
 constructor(height, width) {
   this.height = height;
   this.width = width;
}
};

函数声明和类声明之间的一个重要区别是函数声明会提升,类声明不会

  • 类声明和类表达式的主体都执行在严格模式下。比如,构造函数,静态方法,原型方法,getter和setter都在严格模式下执行。

  • constructor方法是一个特殊的方法,这种方法用于创建和初始化一个由class创建的对象。一个类只能拥有一个名为 “constructor”的特殊方法。

原型方法

class Rectangle {
   // constructor
   constructor(height, width) {
       this.height = height;
       this.width = width;
  }
   // Getter
   get area() {
       return this.calcArea()
  }
   // Method
   calcArea() {
       return this.height * this.width;
  }
}

静态方法

static 关键字用来定义一个类的一个静态方法。调用静态方法不需要实例化该类,但不能通过一个类实例调用静态方法。静态方法通常用于为一个应用程序创建工具函数。

class Point {
   constructor(x, y) {
       this.x = x;
       this.y = y;
  }

   static distance(a, b) {
       const dx = a.x - b.x;
       const dy = a.y - b.y;

       return Math.hypot(dx, dy);
  }
}

当一个对象调用静态或原型方法时,如果该对象没有“this”值(或“this”作为布尔,字符串,数字,未定义或null) ,那么“this”值在被调用的函数内部将为 undefined

extends创建子类

extends 关键字在类声明或类表达式中用于创建一个类作为另一个类的一个子类。

super调用父类的函数

super 关键字用于调用对象的父对象上的函数。

species覆盖默认构造函数

species 关键字允许你覆盖默认的构造函数。

在数组类 *MyArray* 中返回 Array对象。
class MyArray extends Array {
 static get [Symbol.species]() { return Array; }
}
var a = new MyArray(1,2,3);
var mapped = a.map(x => x * x);

console.log(mapped instanceof MyArray);
// false
console.log(mapped instanceof Array);  
// true

Mix-ins混合继承

一个子类只能继承父类拥有的一个函数,所以只能这样写

var calculatorMixin = Base => class extends Base {
 calc() { }
};

var randomizerMixin = Base => class extends Base {
 randomize() { }
};

而使用mix-ins的类要这样写

class Foo { }
class Bar extends calculatorMixin(randomizerMixin(Foo)) { }

把父类拥有的一个函数作为参数传递给父类拥有的另一个参数。

 

  

posted @ 2019-08-13 20:24  Irelia9102  阅读(117)  评论(0编辑  收藏  举报