ECMAScript 2015 - Class

一,Class

概述

ES6 之前,我们可以通过构造函数来生成新的对象。

1
2
3
4
5
6
7
8
function Point(x,y){
this.x = x;
this.y = y;
}

Point.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')';
}

ES6 引入了 Class 的概念,我们可以通过 Class 关键字更清晰,面向对象的定义类。

1
2
3
4
5
6
7
8
9
10
11
12
class Point {
// ES5 中的 构造函数,变成了 ES6 中的构造方法 constructor
constructor(x, y) {
this.x = x;
this.y = y;
}

// ES5 中定义在构造函数 prototype 上的共享方法,现在可以直接定义在 Class 内部
toString() { // 类方法前不用写 function
return '(' + this.x + ', ' + this.y + ')';
}
}

ES6 中的 Class,只是一个语法糖,可以看做是构造函数的另一种写法。

Class 也具有 prototype 属性,可以向其添加新方法,同在 Class 内部定义方法的区别在于:

Class 的内部所有定义的方法,都是不可枚举的(non-enumerable)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Point {
constructor(x, y) {
// ...
}

toString() {
// ...
}
}
Point.prototype.toValue = function () {
// ...
}
Object.keys(Point.prototype) // 返回可枚举自身属性名的数组
// ["toValue"]
Object.getOwnPropertyNames(Point.prototype) // 返回自身属性名的数组,包括不可枚举属性。
// ["constructor","toString","toValue"]

constructor 方法

constructor 方法是 Class 的默认方法,通过 new 命令生成对象实例时,自动调用该方法。

一个 Class 必须有 constructor 方法,如果没有显式定义,一个空的 constructor 方法会被默认添加。

constructor 方法默认返回实例对象(即 this),但也可以指定返回另外一个对象。

1
2
3
4
5
6
7
8
9
class Foo {
constructor() {
return Object.create(null);
}
}

// constructor函数返回一个全新的对象,导致实例对象不是Foo类的实例。
new Foo() instanceof Foo
// false

Class 的实例对象

生成类的实例对象的写法,与 ES5 完全一样,也是使用 new 命令,不加会报错。

实例的属性除非显式定义在 this 对象上,否则都是定义在 Classprototype 上。

Class 的所有实例共享一个原型对象,所以可以通过实例的 __proto__ 属性为 Class 添加方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}

var p1 = new Point(2,3);
var p2 = new Point(3,2);

p1.toString(); // (2, 3)
p1.hasOwnProperty('x'); // true
p1.hasOwnProperty('y'); // true
p1.hasOwnProperty('toString'); // false
p1.__proto__.hasOwnProperty('toString'); // true

p1.__proto__ === p2.__proto__ // true

// 通过 p1.__proto__ 为 Point 添加新共享方法。
p1.__proto__.printName = function () { return 'Oops' };

p1.printName(); // "Oops"
p2.printName(); // "Oops"

var p3 = new Point(4,2);
p3.printName(); // "Oops"

Class 表达式

Class 也可以使用表达式的形式定义。

1
2
3
4
5
6
7
8
9
const MyClass = class Me { // Me 只在 Class 内部有效,可省略
getClassName() {
return Me.name;
}
};

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

采用 Class 表达式,可以写出立即执行的 Class

1
2
3
4
5
6
7
8
9
10
11
let person = new class {
constructor(name) {
this.name = name;
}

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

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

不存在变量提升

Class 不存在变量提升,这一点与 function 完全不同,所以必须保证子类在父类之后定义。

严格模式

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

二,extends

基本用法

Class 之间可以通过 extends 关键字实现继承。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Point { // 父类
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}

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

let cp = new ColorPoint(25, 8, 'green');

cp instanceof ColorPoint // true
cp instanceof Point // true
注意点:

1,子类必须在 constructor 方法中调用 super 方法,否则新建实例时会报错。
这是因为子类没有自己的 this 对象,而是继承父类的 this 对象,然后对其进行加工。

2,如果子类没有定义 constructor 方法,这个方法会被默认添加。
也就是说,不管有没有显式定义,任何一个子类都有 constructor 方法。

1
2
3
constructor(...args) {
super(...args);
}

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

继承机制

ES5:实质是先创造子类的实例对象 this,然后再将父类的方法添加到 this 上面(Parent.apply(this))。

ES6:实质是先创造父类的实例对象 this(所以必须先调用 super 方法),然后再用子类的构造函数修改 this

类的 prototype 属性和 __proto__ 属性

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

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

2,子类 prototype 属性的 __proto__ 属性,表示共享方法的继承,总是指向父类的 prototype 属性。
ES5 中,构造函数之间的继承,只有该条继承链

1
2
3
4
5
6
7
class A {}
class B extends A {}

// 子类B的__proto__属性指向父类A
B.__proto__ === A // true
// 子类B的prototype属性(原型对象)的__proto__属性指向父类A的prototype属性(原型对象)
B.prototype.__proto__ === A.prototype // true

类的继承是按照下面的模式实现的。

1
2
3
4
5
6
7
8
9
10
11
class A {}
class B {}

// B的实例继承A的实例
Object.setPrototypeOf(B.prototype, A.prototype);
// 等同于
B.prototype.__proto__ = A.prototype;
// B继承A的静态属性
Object.setPrototypeOf(B, A);
// 等同于
B.__proto__ = A;

这两条继承链,可以这样理解:

作为一个对象Class B 的原型(__proto__ 属性)是 Class A
作为一个构造函数Class B 的原型(prototype 属性)是 Class A 的实例。

1
2
3
B.prototype = new A();
// 等同于
B.prototype.__proto__ = A.prototype;

Extends 的继承目标

extends 关键字后面可以跟多种类型的值,任意函数都能被继承。

三种特殊情况:

1,子类继承 Object

1
2
3
4
class A extends Object {}

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

Class A 是构造函数 Object 的复制,Class A 的实例就是 Object 的实例。

2,不存在任何继承

1
2
3
4
class A {}

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

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

3,子类继承 null

1
2
3
4
class A extends null {}

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

Class A 也是一个普通函数,所以直接继承 Funciton.prototype
Class A 调用后返回的对象不继承任何方法,所以它的 __proto__ 指向 Function.prototype
即实质上执行了下面的代码。

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

Object.getPrototypeOf()

Object.getPrototypeOf() 方法可以用来从子类上获取父类。

super 关键字

super 关键字,有两种用法:

1,作为函数调用时,super 代表父类的构造函数。

2,作为对象调用时,super 代表父类。
此时 super 即可以引用父类实例的属性和方法,也可以引用父类的静态方法。

由于,对象总是继承其他对象的,所以可以在任意一个对象中,使用 super 关键字。

1
2
3
4
5
6
7
var obj = {
toString() {
return "MyObject: " + super.toString();
}
}

obj.toString(); // MyObject: [object Object]

实例的 __proto__ 属性

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

因此,通过子类实例的 __proto__.__proto__ 属性,可以修改父类实例的行为(慎用)。

1
2
3
4
5
6
7
8
9
10
11
var p1 = new Point(2, 3);
var p2 = new ColorPoint(2, 3, 'red');

p2.__proto__ === p1.__proto__ // false
p2.__proto__.__proto__ === p1.__proto__ // true

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

p1.printName() // "Ha"

三,原生构造函数的继承

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

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

由于继承机制的不同,在ES6 以前,原生构造函数无法被继承(子类无法获得其内部属性)。

分析:

ES5 是先创造子类的实例对象 this,再将父类的属性添加到子类上,
这里,由于父类的内部属性无法获取,导致无法真正继承原生构造函数。

ES6 是先创造父类的实例对象 this,再用子类的构造函数修改 this
使得父类的所有属性都可以继承。

利用 extends 可以继承原生构造函数的特性,可以在原生数据结构的基础上,定义自己的数据结构。

实例一:带版本功能的数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class VersionedArray extends Array {
constructor() {
super();
this.history = [[]];
}
commit() { // 通过commit方法,将自己的当前状态存入history属性。
this.history.push(this.slice());
}
revert() { // 通过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]

实例二:自定义Error子类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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 // true
myerror.name // "MyError"
myerror.stack
// Error
// at MyError.ExtendableError
// ...

注意:继承Object的子类,有一个行为差异

1
2
3
4
5
6
7
class NewObj extends Object{
constructor(){
super(...arguments);
}
}
var o = new NewObj({attr: true});
console.log(o.attr === true); // false

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

Class 内部可以使用 getset 关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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

五,ClassGenerator 方法

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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

Generator, yield, Iterator, SymbolES6 中的技术,会在以后的文章中细说。

六,Class 的静态方法

类相当于实例的原型,所有在类中定义的方法,都会被实例继承。
静态方法:使用 static 关键字可以在类中定义静态方法,该方法可以在类还没有实例化时被调用,但不可以在类实例化后调用。静态方法经常作为程序的工具函数使用

静态方法不能在实例中调用,但可以被子类继承,也可以通过 super 对象调用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Tripple {
static tripple(n) {
n = n || 1;
return n * 3;
}
}

class BiggerTripple extends Tripple {
static tripple(n) {
return super.tripple(n) * super.tripple(n);
}
}

console.log(Tripple.tripple()); // 3
console.log(Tripple.tripple(6)); // 18
console.log(BiggerTripple.tripple(3)); // 81
var tp = new Tripple();
console.log(BiggerTripple.tripple(3)); // 81(不会受父类被实例化的影响)
console.log(tp.tripple()); // 'tp.tripple is not a function'.

七,Class 的静态属性和实例属性

静态属性指的是 Class 本身的属性,而不是定义在实例对象(this)上的属性。

ES6 中,Class 内部只有静态方法,没有静态属性,在 Class 内部定义的属性都是无效的。

只能在 Class 的外部通过 Class.propname 的方式定义。

ES7 中,有一个关于静态属性的提案,目前 Babel 转码器支持。

类的实例属性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// ES6 中,只能在类的 constructor 方法里定义实例属性。
class ReactCounter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
}

// ES7 中,类的实例属性可以用等式,写入类的定义之中。
class ReactCounter extends React.Component {
constructor(props) {
super(props);
}
state = {
count: 0
};
}
// 或者,为了可读性的目的,对于那些在 constructor 里面已经定义的实例属性,新写法允许直接列出。
class ReactCounter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
state;
}
类的静态属性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// ES6 中,只能在类的外部定义静态属性。
class Foo {
prop1: 2 // 写法一,无效,但不会报错
static prop2: 2 // 写法二,无效,但不会报错
}
Foo.prop1 // undefined
Foo.prop2 // undefined
Foo.prop3 = 1;
Foo.prop3 // 1

// ES7 中,只要在实例属性写法前面,加上 static 关键字就可以了。
class MyClass {
static myStaticProp = 42;

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

八,new.target 属性

new 是从构造函数生成实例的命令。
ES6 为 new 命令引入了一个 new.target 属性,返回 new 命令作用于的那个构造函数。
如果构造函数不是通过 new 命令调用的,new.target 会返回 undefined

在函数外部,使用 new.target 会报错。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// 在构造函数中调用
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, '张三'); // 报错

// 在 Class 中调用
class Rectangle {
constructor(length, width) {
console.log(new.target === Rectangle);
this.length = length;
this.width = width;
}
}

var obj1 = new Rectangle(3, 4); // 输出 true

// 子类继承父类时,new.target会返回子类。
class Square extends Rectangle {
constructor(length) {
super(length, length);
}
}

var obj2 = new Square(3); // 输出 false

应用:不能独立使用、必须继承后才能使用的类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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); // 正确

九,Mixin 模式的实现

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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) {
// ...
}

参考:

阮一峰:ECMAScript 6 入门 - Class

MDN:Classes