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);

下面这种写法跟传统的面向对象语言(比方C++和Java)差别很大,很容易让新学习这门语言的程序员感到困惑。

ES6提供了更靠近传统语言的写法,引入了Class(类)这个概念,作为对象的模板。通过class关键字,能够定义类。基本上,ES6的class能够看作只是一个语法糖,它的绝大部分性能,ES5都能够做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。下面的代码用ES6的“类”改写,就是上面这样。

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

下面代码定义了一个“类”,能够看到外面有一个constructor办法,这就是构造方法,而this关键字则代表实例对象。也就是说,ES5的构造函数Point,对应ES6的Point类的构造方法。

Point类除了构造方法,还定义了一个toString办法。留神,定义“类”的办法的时候,后面不须要加上function这个关键字,间接把函数定义放进去了就能够了。另外,办法之间不须要逗号分隔,加了会报错。

ES6的类,齐全能够看作构造函数的另一种写法。

class Point {  // ...}typeof Point // "function"Point === Point.prototype.constructor // true

下面代码表明,类的数据类型就是函数,类自身就指向构造函数。

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

class Bar {  doStuff() {    console.log('stuff');  }}var b = new Bar();b.doStuff() // "stuff"

构造函数的prototype属性,在ES6的“类”下面持续存在。事实上,类的所有办法都定义在类的prototype属性下面。

class Point {  constructor(){    // ...  }  toString(){    // ...  }  toValue(){    // ...  }}// 等同于Point.prototype = {  toString(){},  toValue(){}};

在类的实例下面调用办法,其实就是调用原型上的办法。

class B {}let b = new B();b.constructor === B.prototype.constructor // true

下面代码中,b是B类的实例,它的constructor办法就是B类原型的constructor办法。

因为类的办法都定义在prototype对象下面,所以类的新办法能够增加在prototype对象下面。Object.assign办法能够很不便地一次向类增加多个办法。

class Point {  constructor(){    // ...  }}Object.assign(Point.prototype, {  toString(){},  toValue(){}});

prototype对象的constructor属性,间接指向“类”的自身,这与ES5的行为是统一的。

Point.prototype.constructor === Point // true

另外,类的外部所有定义的办法,都是不可枚举的(non-enumerable)。

class Point {  constructor(x, y) {    // ...  }  toString() {    // ...  }}Object.keys(Point.prototype)// []Object.getOwnPropertyNames(Point.prototype)// ["constructor","toString"]

下面代码中,toString办法是Point类外部定义的办法,它是不可枚举的。这一点与ES5的行为不统一。

var Point = function (x, y) {  // ...};Point.prototype.toString = function() {  // ...};Object.keys(Point.prototype)// ["toString"]Object.getOwnPropertyNames(Point.prototype)// ["constructor","toString"]

下面代码采纳ES5的写法,toString办法就是可枚举的。

类的属性名,能够采纳表达式。

let methodName = "getArea";class Square{  constructor(length) {    // ...  }  [methodName]() {    // ...  }}

下面代码中,Square类的办法名getArea,是从表达式失去的。

constructor办法

constructor办法是类的默认办法,通过new命令生成对象实例时,主动调用该办法。一个类必须有constructor办法,如果没有显式定义,一个空的constructor办法会被默认增加。

constructor() {}

constructor办法默认返回实例对象(即this),齐全能够指定返回另外一个对象。

class Foo {  constructor() {    return Object.create(null);  }}new Foo() instanceof Foo// false

下面代码中,constructor函数返回一个全新的对象,后果导致实例对象不是Foo类的实例。

类的构造函数,不应用new是没法调用的,会报错。这是它跟一般构造函数的一个次要区别,后者不必new也能够执行。

class Foo {  constructor() {    return Object.create(null);  }}Foo()// TypeError: Class constructor Foo cannot be invoked without 'new'

类的实例对象

生成类的实例对象的写法,与ES5齐全一样,也是应用new命令。如果遗记加上new,像函数那样调用Class,将会报错。

// 报错var point = Point(2, 3);// 正确var point = new Point(2, 3);

与ES5一样,实例的属性除非显式定义在其自身(即定义在this对象上),否则都是定义在原型上(即定义在class上)。

//定义类class Point {  constructor(x, y) {    this.x = x;    this.y = y;  }  toString() {    return '(' + this.x + ', ' + this.y + ')';  }}var point = new Point(2, 3);point.toString() // (2, 3)point.hasOwnProperty('x') // truepoint.hasOwnProperty('y') // truepoint.hasOwnProperty('toString') // falsepoint.__proto__.hasOwnProperty('toString') // true

下面代码中,xy都是实例对象point本身的属性(因为定义在this变量上),所以hasOwnProperty办法返回true,而toString是原型对象的属性(因为定义在Point类上),所以hasOwnProperty办法返回false。这些都与ES5的行为保持一致。

与ES5一样,类的所有实例共享一个原型对象。

var p1 = new Point(2,3);var p2 = new Point(3,2);p1.__proto__ === p2.__proto__//true

下面代码中,p1p2都是Point的实例,它们的原型都是Point.prototype,所以__proto__属性是相等的。

这也意味着,能够通过实例的__proto__属性为Class增加办法。

var p1 = new Point(2,3);var p2 = new Point(3,2);p1.__proto__.printName = function () { return 'Oops' };p1.printName() // "Oops"p2.printName() // "Oops"var p3 = new Point(4,2);p3.printName() // "Oops"

下面代码在p1的原型上增加了一个printName办法,因为p1的原型就是p2的原型,因而p2也能够调用这个办法。而且,尔后新建的实例p3也能够调用这个办法。这意味着,应用实例的__proto__属性改写原型,必须相当审慎,不举荐应用,因为这会扭转Class的原始定义,影响到所有实例。

不存在变量晋升

Class不存在变量晋升(hoist),这一点与ES5齐全不同。

new Foo(); // ReferenceErrorclass Foo {}

下面代码中,Foo类应用在前,定义在后,这样会报错,因为ES6不会把类的申明晋升到代码头部。这种规定的起因与下文要提到的继承无关,必须保障子类在父类之后定义。

{  let Foo = class {};  class Bar extends Foo {  }}

下面的代码不会报错,因为Bar继承Foo的时候,Foo曾经有定义了。然而,如果存在class的晋升,下面代码就会报错,因为class会被晋升到代码头部,而let命令是不晋升的,所以导致Bar继承Foo的时候,Foo还没有定义。

Class表达式

与函数一样,类也能够应用表达式的模式定义。

const MyClass = class Me {  getClassName() {    return Me.name;  }};

下面代码应用表达式定义了一个类。须要留神的是,这个类的名字是MyClass而不是MeMe只在Class的外部代码可用,指代以后类。

let inst = new MyClass();inst.getClassName() // MeMe.name // ReferenceError: Me is not defined

下面代码示意,Me只在Class外部有定义。

如果类的外部没用到的话,能够省略Me,也就是能够写成上面的模式。

const MyClass = class { /* ... */ };

采纳Class表达式,能够写出立刻执行的Class。

let person = new class {  constructor(name) {    this.name = name;  }  sayName() {    console.log(this.name);  }}('张三');person.sayName(); // "张三"

下面代码中,person是一个立刻执行的类的实例。

公有办法

公有办法是常见需要,但ES6不提供,只能通过变通方法模仿实现。

一种做法是在命名上加以区别。

class Widget {  // 私有办法  foo (baz) {    this._bar(baz);  }  // 公有办法  _bar(baz) {    return this.snaf = baz;  }  // ...}

下面代码中,_bar办法后面的下划线,示意这是一个只限于外部应用的公有办法。然而,这种命名是不保险的,在类的内部,还是能够调用到这个办法。

另一种办法就是索性将公有办法移出模块,因为模块外部的所有办法都是对外可见的。

class Widget {  foo (baz) {    bar.call(this, baz);  }  // ...}function bar(baz) {  return this.snaf = baz;}

下面代码中,foo是私有办法,外部调用了bar.call(this, baz)。这使得bar实际上成为了以后模块的公有办法。

还有一种办法是利用Symbol值的唯一性,将公有办法的名字命名为一个Symbol值。

const bar = Symbol('bar');const snaf = Symbol('snaf');export default class myClass{  // 私有办法  foo(baz) {    this[bar](baz);  }  // 公有办法  [bar](baz) {    return this[snaf] = baz;  }  // ...};

下面代码中,barsnaf都是Symbol值,导致第三方无奈获取到它们,因而达到了公有办法和公有属性的成果。

this的指向

类的办法外部如果含有this,它默认指向类的实例。然而,必须十分小心,一旦独自应用该办法,很可能报错。

class Logger {  printName(name = 'there') {    this.print(`Hello ${name}`);  }  print(text) {    console.log(text);  }}const logger = new Logger();const { printName } = logger;printName(); // TypeError: Cannot read property 'print' of undefined

下面代码中,printName办法中的this,默认指向Logger类的实例。然而,如果将这个办法提取进去独自应用,this会指向该办法运行时所在的环境,因为找不到print办法而导致报错。

一个比较简单的解决办法是,在构造方法中绑定this,这样就不会找不到print办法了。

class Logger {  constructor() {    this.printName = this.printName.bind(this);  }  // ...}

另一种解决办法是应用箭头函数。

class Logger {  constructor() {    this.printName = (name = 'there') => {      this.print(`Hello ${name}`);    };  }  // ...}

还有一种解决办法是应用Proxy,获取办法的时候,主动绑定this

function selfish (target) {  const cache = new WeakMap();  const handler = {    get (target, key) {      const value = Reflect.get(target, key);      if (typeof value !== 'function') {        return value;      }      if (!cache.has(value)) {        cache.set(value, value.bind(target));      }      return cache.get(value);    }  };  const proxy = new Proxy(target, handler);  return proxy;}const logger = selfish(new Logger());

严格模式

类和模块的外部,默认就是严格模式,所以不须要应用use strict指定运行模式。只有你的代码写在类或模块之中,就只有严格模式可用。

思考到将来所有的代码,其实都是运行在模块之中,所以ES6实际上把整个语言降级到了严格模式。

name属性

因为实质上,ES6的类只是ES5的构造函数的一层包装,所以函数的许多个性都被Class继承,包含name属性。

class Point {}Point.name // "Point"

name属性总是返回紧跟在class关键字前面的类名。

Class的继承

根本用法

Class之间能够通过extends关键字实现继承,这比ES5的通过批改原型链实现继承,要清晰和不便很多。

class ColorPoint extends Point {}

下面代码定义了一个ColorPoint类,该类通过extends关键字,继承了Point类的所有属性和办法。然而因为没有部署任何代码,所以这两个类齐全一样,等于复制了一个Point类。上面,咱们在ColorPoint外部加上代码。

class ColorPoint extends Point {  constructor(x, y, color) {    super(x, y); // 调用父类的constructor(x, y)    this.color = color;  }  toString() {    return this.color + ' ' + super.toString(); // 调用父类的toString()  }}

下面代码中,constructor办法和toString办法之中,都呈现了super关键字,它在这里示意父类的构造函数,用来新建父类的this对象。

子类必须在constructor办法中调用super办法,否则新建实例时会报错。这是因为子类没有本人的this对象,而是继承父类的this对象,而后对其进行加工。如果不调用super办法,子类就得不到this对象。

class Point { /* ... */ }class ColorPoint extends Point {  constructor() {  }}let cp = new ColorPoint(); // ReferenceError

下面代码中,ColorPoint继承了父类Point,然而它的构造函数没有调用super办法,导致新建实例时报错。

ES5的继承,本质是先发明子类的实例对象this,而后再将父类的办法增加到this下面(Parent.apply(this))。ES6的继承机制齐全不同,本质是先发明父类的实例对象this(所以必须先调用super办法),而后再用子类的构造函数批改this

如果子类没有定义constructor办法,这个办法会被默认增加,代码如下。也就是说,不论有没有显式定义,任何一个子类都有constructor办法。

constructor(...args) {  super(...args);}

另一个须要留神的中央是,在子类的构造函数中,只有调用super之后,才能够应用this关键字,否则会报错。这是因为子类实例的构建,是基于对父类实例加工,只有super办法能力返回父类实例。

class Point {  constructor(x, y) {    this.x = x;    this.y = y;  }}class ColorPoint extends Point {  constructor(x, y, color) {    this.color = color; // ReferenceError    super(x, y);    this.color = color; // 正确  }}

下面代码中,子类的constructor办法没有调用super之前,就应用this关键字,后果报错,而放在super办法之后就是正确的。

上面是生成子类实例的代码。

let cp = new ColorPoint(25, 8, 'green');cp instanceof ColorPoint // truecp instanceof Point // true

下面代码中,实例对象cp同时是ColorPointPoint两个类的实例,这与ES5的行为完全一致。

类的prototype属性和__proto__属性

大多数浏览器的ES5实现之中,每一个对象都有__proto__属性,指向对应的构造函数的prototype属性。Class作为构造函数的语法糖,同时有prototype属性和__proto__属性,因而同时存在两条继承链。

(1)子类的__proto__属性,示意构造函数的继承,总是指向父类。

(2)子类prototype属性的__proto__属性,示意办法的继承,总是指向父类的prototype属性。

class A {}class B extends A {}B.__proto__ === A // trueB.prototype.__proto__ === A.prototype // true

下面代码中,子类B__proto__属性指向父类A,子类Bprototype属性的__proto__属性指向父类Aprototype属性。

这样的后果是因为,类的继承是依照上面的模式实现的。

class A {}class B {}// B的实例继承A的实例Object.setPrototypeOf(B.prototype, A.prototype);// B继承A的动态属性Object.setPrototypeOf(B, A);

《对象的扩大》一章给出过Object.setPrototypeOf办法的实现。

Object.setPrototypeOf = function (obj, proto) {  obj.__proto__ = proto;  return obj;}

因而,就失去了下面的后果。

Object.setPrototypeOf(B.prototype, A.prototype);// 等同于B.prototype.__proto__ = A.prototype;Object.setPrototypeOf(B, A);// 等同于B.__proto__ = A;

这两条继承链,能够这样了解:作为一个对象,子类(B)的原型(__proto__属性)是父类(A);作为一个构造函数,子类(B)的原型(prototype属性)是父类的实例。

Object.create(A.prototype);// 等同于B.prototype.__proto__ = A.prototype;

Extends 的继承指标

extends关键字前面能够跟多种类型的值。

class B extends A {}

下面代码的A,只有是一个有prototype属性的函数,就能被B继承。因为函数都有prototype属性(除了Function.prototype函数),因而A能够是任意函数。

上面,探讨三种非凡状况。

第一种非凡状况,子类继承Object类。

class A extends Object {}A.__proto__ === Object // trueA.prototype.__proto__ === Object.prototype // true

这种状况下,A其实就是构造函数Object的复制,A的实例就是Object的实例。

第二种非凡状况,不存在任何继承。

class A {}A.__proto__ === Function.prototype // trueA.prototype.__proto__ === Object.prototype // true

这种状况下,A作为一个基类(即不存在任何继承),就是一个一般函数,所以间接继承Funciton.prototype。然而,A调用后返回一个空对象(即Object实例),所以A.prototype.__proto__指向构造函数(Object)的prototype属性。

第三种非凡状况,子类继承null

class A extends null {}A.__proto__ === Function.prototype // trueA.prototype.__proto__ === undefined // true

这种状况与第二种状况十分像。A也是一个一般函数,所以间接继承Funciton.prototype。然而,A调用后返回的对象不继承任何办法,所以它的__proto__指向Function.prototype,即本质上执行了上面的代码。

class C extends null {  constructor() { return Object.create(null); }}

Object.getPrototypeOf()

Object.getPrototypeOf办法能够用来从子类上获取父类。

Object.getPrototypeOf(ColorPoint) === Point// true

因而,能够应用这个办法判断,一个类是否继承了另一个类。

super 关键字

super这个关键字,既能够当作函数应用,也能够当作对象应用。在这两种状况下,它的用法齐全不同。

第一种状况,super作为函数调用时,代表父类的构造函数。ES6 要求,子类的构造函数必须执行一次super函数。

class A {}class B extends A {  constructor() {    super();  }}

下面代码中,子类B的构造函数之中的super(),代表调用父类的构造函数。这是必须的,否则 JavaScript 引擎会报错。

留神,super尽管代表了父类A的构造函数,然而返回的是子类B的实例,即super外部的this指的是B,因而super()在这里相当于A.prototype.constructor.call(this)

class A {  constructor() {    console.log(new.target.name);  }}class B extends A {  constructor() {    super();  }}new A() // Anew B() // B

下面代码中,new.target指向以后正在执行的函数。能够看到,在super()执行时,它指向的是子类B的构造函数,而不是父类A的构造函数。也就是说,super()外部的this指向的是B

作为函数时,super()只能用在子类的构造函数之中,用在其余中央就会报错。

class A {}class B extends A {  m() {    super(); // 报错  }}

下面代码中,super()用在B类的m办法之中,就会造成句法谬误。

第二种状况,super作为对象时,指向父类的原型对象。

class A {  p() {    return 2;  }}class B extends A {  constructor() {    super();    console.log(super.p()); // 2  }}let b = new B();

下面代码中,子类B当中的super.p(),就是将super当作一个对象应用。这时,super指向A.prototype,所以super.p()就相当于A.prototype.p()

这里须要留神,因为super指向父类的原型对象,所以定义在父类实例上的办法或属性,是无奈通过super调用的。

class A {  constructor() {    this.p = 2;  }}class B extends A {  get m() {    return super.p;  }}let b = new B();b.m // undefined

下面代码中,p是父类A实例的属性,super.p就援用不到它。

如果属性定义在父类的原型对象上,super就能够取到。

class A {}A.prototype.x = 2;class B extends A {  constructor() {    super();    console.log(super.x) // 2  }}let b = new B();

下面代码中,属性x是定义在A.prototype下面的,所以super.x能够取到它的值。

ES6 规定,通过super调用父类的办法时,super会绑定子类的this

class A {  constructor() {    this.x = 1;  }  print() {    console.log(this.x);  }}class B extends A {  constructor() {    super();    this.x = 2;  }  m() {    super.print();  }}let b = new B();b.m() // 2

下面代码中,super.print()尽管调用的是A.prototype.print(),然而A.prototype.print()会绑定子类Bthis,导致输入的是2,而不是1。也就是说,实际上执行的是super.print.call(this)

因为绑定子类的this,所以如果通过super对某个属性赋值,这时super就是this,赋值的属性会变成子类实例的属性。

class A {  constructor() {    this.x = 1;  }}class B extends A {  constructor() {    super();    this.x = 2;    super.x = 3;    console.log(super.x); // undefined    console.log(this.x); // 3  }}let b = new B();

下面代码中,super.x赋值为3,这时等同于对this.x赋值为3。而当读取super.x的时候,读的是A.prototype.x,所以返回undefined

留神,应用super的时候,必须显式指定是作为函数、还是作为对象应用,否则会报错。

class A {}class B extends A {  constructor() {    super();    console.log(super); // 报错  }}

下面代码中,console.log(super)当中的super,无奈看出是作为函数应用,还是作为对象应用,所以 JavaScript 引擎解析代码的时候就会报错。这时,如果能清晰地表明super的数据类型,就不会报错。

class A {}class B extends A {  constructor() {    super();    console.log(super.valueOf() instanceof B); // true  }}let b = new B();

下面代码中,super.valueOf()表明super是一个对象,因而就不会报错。同时,因为super绑定Bthis,所以super.valueOf()返回的是一个B的实例。

最初,因为对象总是继承其余对象的,所以能够在任意一个对象中,应用super关键字。

var obj = {  toString() {    return "MyObject: " + super.toString();  }};obj.toString(); // MyObject: [object Object]

实例的__proto__属性

子类实例的__proto__属性的__proto__属性,指向父类实例的__proto__属性。也就是说,子类的原型的原型,是父类的原型。

var p1 = new Point(2, 3);var p2 = new ColorPoint(2, 3, 'red');p2.__proto__ === p1.__proto__ // falsep2.__proto__.__proto__ === p1.__proto__ // true

下面代码中,ColorPoint继承了Point,导致前者原型的原型是后者的原型。

因而,通过子类实例的__proto__.__proto__属性,能够批改父类实例的行为。

p2.__proto__.__proto__.printName = function () {  console.log('Ha');};p1.printName() // "Ha"

下面代码在ColorPoint的实例p2上向Point类增加办法,后果影响到了Point的实例p1

原生构造函数的继承

原生构造函数是指语言内置的构造函数,通常用来生成数据结构。ECMAScript的原生构造函数大抵有上面这些。

  • Boolean()
  • Number()
  • String()
  • Array()
  • Date()
  • Function()
  • RegExp()
  • Error()
  • Object()

以前,这些原生构造函数是无奈继承的,比方,不能自己定义一个Array的子类。

function MyArray() {  Array.apply(this, arguments);}MyArray.prototype = Object.create(Array.prototype, {  constructor: {    value: MyArray,    writable: true,    configurable: true,    enumerable: true  }});

下面代码定义了一个继承Array的MyArray类。然而,这个类的行为与Array齐全不统一。

var colors = new MyArray();colors[0] = "red";colors.length  // 0colors.length = 0;colors[0]  // "red"

之所以会产生这种状况,是因为子类无奈取得原生构造函数的外部属性,通过Array.apply()或者调配给原型对象都不行。原生构造函数会疏忽apply办法传入的this,也就是说,原生构造函数的this无奈绑定,导致拿不到外部属性。

ES5是先新建子类的实例对象this,再将父类的属性增加到子类上,因为父类的外部属性无奈获取,导致无奈继承原生的构造函数。比方,Array构造函数有一个外部属性[[DefineOwnProperty]],用来定义新属性时,更新length属性,这个外部属性无奈在子类获取,导致子类的length属性行为不失常。

上面的例子中,咱们想让一个一般对象继承Error对象。

var e = {};Object.getOwnPropertyNames(Error.call(e))// [ 'stack' ]Object.getOwnPropertyNames(e)// []

下面代码中,咱们想通过Error.call(e)这种写法,让一般对象e具备Error对象的实例属性。然而,Error.call()齐全疏忽传入的第一个参数,而是返回一个新对象,e自身没有任何变动。这证实了Error.call(e)这种写法,无奈继承原生构造函数。

ES6容许继承原生构造函数定义子类,因为ES6是先新建父类的实例对象this,而后再用子类的构造函数润饰this,使得父类的所有行为都能够继承。上面是一个继承Array的例子。

class MyArray extends Array {  constructor(...args) {    super(...args);  }}var arr = new MyArray();arr[0] = 12;arr.length // 1arr.length = 0;arr[0] // undefined

下面代码定义了一个MyArray类,继承了Array构造函数,因而就能够从MyArray生成数组的实例。这意味着,ES6能够自定义原生数据结构(比方Array、String等)的子类,这是ES5无奈做到的。

下面这个例子也阐明,extends关键字不仅能够用来继承类,还能够用来继承原生的构造函数。因而能够在原生数据结构的根底上,定义本人的数据结构。上面就是定义了一个带版本性能的数组。

class VersionedArray extends Array {  constructor() {    super();    this.history = [[]];  }  commit() {    this.history.push(this.slice());  }  revert() {    this.splice(0, this.length, ...this.history[this.history.length - 1]);  }}var x = new VersionedArray();x.push(1);x.push(2);x // [1, 2]x.history // [[]]x.commit();x.history // [[], [1, 2]]x.push(3);x // [1, 2, 3]x.revert();x // [1, 2]

下面代码中,VersionedArray构造会通过commit办法,将本人的以后状态存入history属性,而后通过revert办法,能够撤销以后版本,回到上一个版本。除此之外,VersionedArray仍然是一个数组,所有原生的数组办法都能够在它下面调用。

上面是一个自定义Error子类的例子。

class ExtendableError extends Error {  constructor(message) {    super();    this.message = message;    this.stack = (new Error()).stack;    this.name = this.constructor.name;  }}class MyError extends ExtendableError {  constructor(m) {    super(m);  }}var myerror = new MyError('ll');myerror.message // "ll"myerror instanceof Error // truemyerror.name // "MyError"myerror.stack// Error//     at MyError.ExtendableError//     ...

留神,继承Object的子类,有一个行为差别。

class NewObj extends Object{  constructor(){    super(...arguments);  }}var o = new NewObj({attr: true});console.log(o.attr === true);  // false

下面代码中,NewObj继承了Object,然而无奈通过super办法向父类Object传参。这是因为ES6扭转了Object构造函数的行为,一旦发现Object办法不是通过new Object()这种模式调用,ES6规定Object构造函数会疏忽参数。

Class的取值函数(getter)和存值函数(setter)

与ES5一样,在Class外部能够应用getset关键字,对某个属性设置存值函数和取值函数,拦挡该属性的存取行为。

class MyClass {  constructor() {    // ...  }  get prop() {    return 'getter';  }  set prop(value) {    console.log('setter: '+value);  }}let inst = new MyClass();inst.prop = 123;// setter: 123inst.prop// 'getter'

下面代码中,prop属性有对应的存值函数和取值函数,因而赋值和读取行为都被自定义了。

存值函数和取值函数是设置在属性的descriptor对象上的。

class CustomHTMLElement {  constructor(element) {    this.element = element;  }  get html() {    return this.element.innerHTML;  }  set html(value) {    this.element.innerHTML = value;  }}var descriptor = Object.getOwnPropertyDescriptor(  CustomHTMLElement.prototype, "html");"get" in descriptor  // true"set" in descriptor  // true

下面代码中,存值函数和取值函数是定义在html属性的形容对象下面,这与ES5完全一致。

Class的Generator办法

如果某个办法之前加上星号(*),就示意该办法是一个Generator函数。

class Foo {  constructor(...args) {    this.args = args;  }  * [Symbol.iterator]() {    for (let arg of this.args) {      yield arg;    }  }}for (let x of new Foo('hello', 'world')) {  console.log(x);}// hello// world

下面代码中,Foo类的Symbol.iterator办法前有一个星号,示意该办法是一个Generator函数。Symbol.iterator办法返回一个Foo类的默认遍历器,for...of循环会主动调用这个遍历器。

Class的静态方法

类相当于实例的原型,所有在类中定义的办法,都会被实例继承。如果在一个办法前,加上static关键字,就示意该办法不会被实例继承,而是间接通过类来调用,这就称为“静态方法”。

class Foo {  static classMethod() {    return 'hello';  }}Foo.classMethod() // 'hello'var foo = new Foo();foo.classMethod()// TypeError: foo.classMethod is not a function

下面代码中,Foo类的classMethod办法前有static关键字,表明该办法是一个静态方法,能够间接在Foo类上调用(Foo.classMethod()),而不是在Foo类的实例上调用。如果在实例上调用静态方法,会抛出一个谬误,示意不存在该办法。

父类的静态方法,能够被子类继承。

class Foo {  static classMethod() {    return 'hello';  }}class Bar extends Foo {}Bar.classMethod(); // 'hello'

下面代码中,父类Foo有一个静态方法,子类Bar能够调用这个办法。

静态方法也是能够从super对象上调用的。

class Foo {  static classMethod() {    return 'hello';  }}class Bar extends Foo {  static classMethod() {    return super.classMethod() + ', too';  }}Bar.classMethod();

Class的动态属性和实例属性

动态属性指的是Class自身的属性,即Class.propname,而不是定义在实例对象(this)上的属性。

class Foo {}Foo.prop = 1;Foo.prop // 1

下面的写法为Foo类定义了一个动态属性prop

目前,只有这种写法可行,因为ES6明确规定,Class外部只有静态方法,没有动态属性。

// 以下两种写法都有效class Foo {  // 写法一  prop: 2  // 写法二  static prop: 2}Foo.prop // undefined

ES7有一个动态属性的提案,目前Babel转码器反对。

这个提案对实例属性和动态属性,都规定了新的写法。

(1)类的实例属性

类的实例属性能够用等式,写入类的定义之中。

class MyClass {  myProp = 42;  constructor() {    console.log(this.myProp); // 42  }}

下面代码中,myProp就是MyClass的实例属性。在MyClass的实例上,能够读取这个属性。

以前,咱们定义实例属性,只能写在类的constructor办法外面。

class ReactCounter extends React.Component {  constructor(props) {    super(props);    this.state = {      count: 0    };  }}

下面代码中,构造方法constructor外面,定义了this.state属性。

有了新的写法当前,能够不在constructor办法外面定义。

class ReactCounter extends React.Component {  state = {    count: 0  };}

这种写法比以前更清晰。

为了可读性的目标,对于那些在constructor外面曾经定义的实例属性,新写法容许间接列出。

class ReactCounter extends React.Component {  constructor(props) {    super(props);    this.state = {      count: 0    };  }  state;}

(2)类的动态属性

类的动态属性只有在下面的实例属性写法后面,加上static关键字就能够了。

class MyClass {  static myStaticProp = 42;  constructor() {    console.log(MyClass.myProp); // 42  }}

同样的,这个新写法大大不便了动态属性的表白。

// 老写法class Foo {}Foo.prop = 1;// 新写法class Foo {  static prop = 1;}

下面代码中,老写法的动态属性定义在类的内部。整个类生成当前,再生成动态属性。这样让人很容易疏忽这个动态属性,也不合乎相干代码应该放在一起的代码组织准则。另外,新写法是显式申明(declarative),而不是赋值解决,语义更好。

new.target属性

new是从构造函数生成实例的命令。ES6为new命令引入了一个new.target属性,(在构造函数中)返回new命令作用于的那个构造函数。如果构造函数不是通过new命令调用的,new.target会返回undefined,因而这个属性能够用来确定构造函数是怎么调用的。

function Person(name) {  if (new.target !== undefined) {    this.name = name;  } else {    throw new Error('必须应用new生成实例');  }}// 另一种写法function Person(name) {  if (new.target === Person) {    this.name = name;  } else {    throw new Error('必须应用new生成实例');  }}var person = new Person('张三'); // 正确var notAPerson = Person.call(person, '张三');  // 报错

下面代码确保构造函数只能通过new命令调用。

Class外部调用new.target,返回以后Class。

class Rectangle {  constructor(length, width) {    console.log(new.target === Rectangle);    this.length = length;    this.width = width;  }}var obj = new Rectangle(3, 4); // 输入 true

须要留神的是,子类继承父类时,new.target会返回子类。

class Rectangle {  constructor(length, width) {    console.log(new.target === Rectangle);    // ...  }}class Square extends Rectangle {  constructor(length) {    super(length, length);  }}var obj = new Square(3); // 输入 false

下面代码中,new.target会返回子类。

利用这个特点,能够写出不能独立应用、必须继承后能力应用的类。

class Shape {  constructor() {    if (new.target === Shape) {      throw new Error('本类不能实例化');    }  }}class Rectangle extends Shape {  constructor(length, width) {    super();    // ...  }}var x = new Shape();  // 报错var y = new Rectangle(3, 4);  // 正确

下面代码中,Shape类不能被实例化,只能用于继承。

留神,在函数内部,应用new.target会报错。

Mixin模式的实现

Mixin模式指的是,将多个类的接口“混入”(mix in)另一个类。它在ES6的实现如下。

function mix(...mixins) {  class Mix {}  for (let mixin of mixins) {    copyProperties(Mix, mixin);    copyProperties(Mix.prototype, mixin.prototype);  }  return Mix;}function copyProperties(target, source) {  for (let key of Reflect.ownKeys(source)) {    if ( key !== "constructor"      && key !== "prototype"      && key !== "name"    ) {      let desc = Object.getOwnPropertyDescriptor(source, key);      Object.defineProperty(target, key, desc);    }  }}

下面代码的mix函数,能够将多个对象合成为一个类。应用的时候,只有继承这个类即可。

class DistributedEdit extends mix(Loggable, Serializable) {  // ...}