ES6 (11):Class

ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。(所以其实不要和面向对象的class 混为一谈,因为并不是真正意义上的类)

ES5:(之前的博文中有记录过this,优先级new 是最高的,并且如果是new 方法创建的实例,等于是复制了一份,this指向自身)

 constructor构造方法,this关键字则代表实例对象(与ES5 一致)

class 创建的类与ES5 中创建的函数有所不同,下面如果直接执行call 方法,提示类的构造器不能没有new 去执行,必须要创建实例才可以。

类的数据类型就是函数,类本身就指向构造函数

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

class B {}
let b = new B();

b.constructor === B.prototype.constructor // true

 由于类的方法都定义在prototype对象上面,所以类的新方法可以添加在prototype对象上面。Object.assign方法可以很方便地一次向类添加多个方法。

class Point {
  constructor(){
    // ...
  }
}

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

 

设置对象原型的时候,a 丢到了Point 类的构造方法的原型中。

prototype对象的constructor属性,直接指向“类”的本身,这与 ES5 的行为是一致的。

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

 内部所有定义的方法,都是不可枚举的(non-enumerable)。这一点与 ES5(可枚举) 的行为不一致。

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') // true
point.hasOwnProperty('y') // true
point.hasOwnProperty('toString') // false
point.__proto__.hasOwnProperty('toString') // true

getter、setter:

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

let inst = new MyClass();

inst.prop = 123;
// setter: 123

inst.prop
// 'getter'

类的属性名,可以采用表达式。

let methodName = 'getArea';

class Square {
  constructor(length) {
    // ...
  }

  [methodName]() {
    // ...
  }
}

 

 表达式:(有点像函数)

const MyClass = class Me {
  getClassName() {
    return Me.name;
  }
};
const MyClass1 = class{
  getClassName() {
    return Me.name;
  }
};
const foo = function test(){}

 

采用 Class 表达式,可以写出立即执行的 Class(必须要有new)。

let person = new class {
  constructor(name) {
    this.name = name;
  }

  sayName() {
    console.log(this.name);
  }
}('张三');

person.sayName(); // "张三"

类和模块的内部,默认就是严格模式,所以不需要使用use strict指定运行模式。

类不存在变量提升(hoist),这一点与 ES5 完全不同。

变量提升到全局window。(作为使用new 创建的对象实例,本身this也是指向自身)

 由于本质上,ES6 的类只是 ES5 的构造函数的一层包装,所以函数的许多特性都被Class继承,包括name属性

如果某个方法之前加上星号(*),就表示该方法是一个 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

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

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

class Foo {
  static classMethod() {
    return 'hello';
  }
}

Foo.classMethod() // 'hello'

var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function
class Foo {
  static bar() {
    this.baz();
  }
  static baz() {
    console.log('hello');
  }
  baz() {
    console.log('world');
  }
}

Foo.bar() // hello

类可以被继承(extend):Bar继承了Foo 类,Bar的原型指向Foo

静态方法也是可以从super对象上调用的(非静态方法也可以)。

class Foo {
  static classMethod() {
    return 'hello';
  }
}

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

Bar.classMethod() // "hello, too"

实例属性除了定义在constructor()方法里面的this上面,也可以定义在类的最顶层(注意没有this)。

class IncreasingCounter {
  _count = 0;
  get value() {
    console.log('Getting the current value!');
    return this._count;
  }
  increment() {
    this._count++;
  }
}

静态属性指的是 Class 本身的属性,即Class.propName,而不是定义在实例对象(this)上的属性(第一种跟ES5 之前一样)。

class Foo {
}

Foo.prop = 1;
Foo.prop // 1

 目前最新的写法。

class MyClass {
  static myStaticProp = 42;

  constructor() {
    console.log(MyClass.myStaticProp); // 42
  }
}

私有方法和私有属性(class 暂不直接支持,只有通过变通的方法,因为class 其内部this本身就是指向实例自身)

ES5:

ES6:

class Widget {
  foo (baz) {
    bar.call(this, baz);
  }

  // ...
}

function bar(baz) {
  return this.snaf = baz;
}

 bar 成为了类的私有方法。

私有属性提案(chrom最新版可以使用了,火狐67.0 未支持)class加了私有属性。方法是在属性名之前,使用#表示,内部使用this.#xxx 访问。

对比:

 私有方法:貌似暂时不支持

 new是从构造函数生成实例对象的命令。ES6 为new命令引入了一个new.target属性,该属性一般用在构造函数之中,返回new命令作用于的那个构造函数。如果构造函数不是通过new命令或Reflect.construct()调用的new.target会返回undefined因此这个属性可以用来确定构造函数是怎么调用的

 利用这个特点,可以写出不能独立使用、必须继承后才能使用的类(子类继承父类时,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);  // 正确

继承:子类的构造方法中必须调用super方法,否则会报错(子类的this对象必须先通过父类的构造函数)

ES5 的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this上面(Parent.apply(this)。ES6 的继承机制完全不同,实质是先将父类实例对象的属性和方法,加到this上面(所以必须先调用super方法),然后再用子类的构造函数修改this

class ColorPoint extends Point {
}

// 等同于
class ColorPoint extends Point {
  constructor(...args) {
    super(...args);
  }
}

在子类的构造函数中,只有调用super之后,才可以使用this关键字,否则会报错。这是因为子类实例的构建,基于父类实例,只有super方法才能调用父类实例。

Object.getPrototypeOf方法可以用来从子类上获取父类(之前有截图,继承的子类的原型对象指向父类)。

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

注意,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() // A
new B() // B

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

 super作为对象时,在普通方法中,指向父类的原型对象;在静态方法中,指向父类。(原型对象)

由于super指向父类的原型对象,所以定义在父类实例上的方法或属性,是无法通过super调用的。

 

 在子类普通方法中通过super调用父类的方法时,方法内部的this指向当前的子类实例。(从下面可以看出,实例中this.x 值被替换为2)

由于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调用父类的方法时,方法内部的this指向当前的子类,而不是子类的实例

prototype 原型对象与__proto__:

class A {
}

class B {
}

// B 的实例继承 A 的实例
Object.setPrototypeOf(B.prototype, A.prototype);

// B 继承 A 的静态属性
Object.setPrototypeOf(B, A);

const b = new B();
class A {
}

class B {
}

// B 的实例继承 A 的实例
Object.setPrototypeOf(B.prototype, A.prototype);

// B 继承 A 的静态属性
Object.setPrototypeOf(B, A);

const b = new B();

 作为一个对象,子类(B)的原型(__proto__属性)是父类(A);作为一个构造函数,子类(B)的原型对象(prototype属性)是父类的原型对象(prototype属性)的实例。(要区分开是作为构造函数还是对象,继承了2条链,继承会绑定和修改this,因为prototype 与__proto__ 本来意思都不能混为一谈)

setPrototype实现:

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

第一种,子类继承Object类。

class A extends Object {
}

A.__proto__ === Object // true
A.prototype.__proto__ === Object.prototype // true

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

第二种情况,不存在任何继承。

class A {
}

A.__proto__ === Function.prototype // true
A.prototype.__proto__ === Object.prototype // true

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

__proto__ 属性:

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

原生构造函数:

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

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

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

ES6 允许继承原生构造函数定义子类,因为 ES6 是先新建父类的实例对象this,然后再用子类的构造函数修饰this使得父类的所有行为都可以继承。

 

下面是阮大神的数组例子(好用哦)

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.history // [[], [1, 2]]

x.revert();
x // [1, 2]

 mixin 混合模式:下面是大神的例子(有点晕)

Mixin 指的是多个对象合成一个新的对象,新对象具有各个组成成员的接口。。

function mix(...mixins) {
  class Mix {
    constructor() {
      for (let mixin of mixins) {
        copyProperties(this, new mixin()); // 拷贝实例属性
      }
    }
  }

  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) { // ... }

成灰之前,抓紧时间做点事!!
原文地址:https://www.cnblogs.com/jony-it/p/10981103.html