1、简介
Class 可以通过 extends 关键字实现继承,这比 ES5 的通过修改原型链实现继承,要清晰和方便很多。
// 通过 extends 关键字继承了 Point 类的所有属性和方法。但是由于没有部署任何代码,所以这两个类完全一样,等于复制了一个 Point 类
class Point {
}
class ColorPoint extends Point {
}
// constructor 方法和 toString 方法之中,都出现了 super 关键字,它在这里表示父类的构造函数,用来新建父类的 this 对象
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 方法中调用 super 方法,否则新建实例时会报错
class Point { /* ... */ }
class ColorPoint extends Point {
constructor() { // 子类没有自己的 this 对象,而是继承父类的 this 对象,然后对其进行加工
}
}
let cp = new ColorPoint(); // ReferenceError,如果不调用 super 方法,子类就得不到 this 对象
// ES5 的继承,实质是先创造子类的实例对象 this,然后再将父类的方法添加到 this上面(Parent.apply(this))。ES6 的继承机制完全不同,实质
// 是先创造父类的实例对象 this(所以必须先调用 super 方法),然后再用子类的构造函数修改 this。
// 如果子类没有定义 constructor 方法,这个方法会被默认添加
class ColorPoint extends Point {
}
class ColorPoint extends Point { // 等同于(不管有没有显式定义,任何一个子类都有 constructor 方法)
constructor(...args) {
super(...args);
}
}
// 在子类的构造函数中,只有调用 super 之后,才可以使用 this 关键字,否则会报错
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); // 子类实例的构建,是基于对父类实例加工,只有 super 方法才能返回父类实例
this.color = color; // 正确
}
}
// 生成子类实例(与 ES5 的行为完全一致)
let cp = new ColorPoint(25, 8, 'green');
cp instanceof ColorPoint // true
cp instanceof Point // true
// 父类的静态方法也会被子类继承
class A {
static hello() { // hello() 是 A 类的静态方法,B 继承 A,也继承了 A 的静态方法
console.log('hello world');
}
}
class B extends A {
}
B.hello() // hello world
2、Object.getPrototypeOf() & super 关键字
Object.getPrototypeOf 方法可以用来从子类上获取父类。因此,可以使用这个方法判断,一个类是否继承了另一个类。
super 这个关键字,既可以当作函数使用,也可以当作对象使用。在这两种情况下,它的用法完全不同。
// 从子类上获取父类
Object.getPrototypeOf(ColorPoint) === Point // true
// super 作为函数调用时,代表父类的构造函数(super 虽然代表了父类的构造函数,但是返回的是子类的实例,即 super 内部的 this 指的是子类)
class A {}
class B extends A {
constructor() { // ES6 要求,子类的构造函数必须执行一次 super 函数
super(); // super() 在这里相当于 A.prototype.constructor.call(this)
}
}
// new.target 指向当前正在执行的函数(在 super() 执行时,它指向的是子类 B 的构造函数,而不是父类 A 的构造函数)
class A {
constructor() {
console.log(new.target.name);
}
}
class B extends A {
constructor() {
super();
}
}
new A() // A
new B() // B
// 作为函数时,super() 只能用在子类的构造函数之中,用在其他地方就会报错
class A {}
class B extends A {
m() {
super(); // 报错
}
}
// super 作为对象时,在普通方法中指向父类的原型对象
class A {
p() {
return 2;
}
}
class B extends A {
constructor() {
super();
console.log(super.p()); // 2,将 super 当作一个对象使用。这时,super 在普通方法之中,指向 A.prototype,所以 super.p() 就相当于 A.prototype.p()
}
}
let b = new B();
// 由于 super 指向父类的原型对象,所以定义在父类实例上的方法或属性,是无法通过 super 调用的
class A {
constructor() {
this.p = 2;
}
}
class B extends A {
get m() {
return super.p; // p 是父类 A 实例的属性,super.p 就引用不到它
}
}
let b = new B();
b.m // undefined
// 如果属性定义在父类的原型对象上,super 就可以取到
class A {}
A.prototype.x = 2;
class B extends A {
constructor() {
super();
console.log(super.x) // 2,属性 x 是定义在 A.prototype 上面的,所以 super.x 可以取到它的值
}
}
let b = new B();
// ES6 规定,通过 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(); // 实际上执行的是 super.print.call(this)
}
}
let b = new B();
b.m() // 2
// 由于 this 指向子类,所以如果通过 super 对某个属性赋值,这时 super 就是 this,赋值的属性会变成子类实例的属性
class A {
constructor() {
this.x = 1;
}
}
class B extends A {
constructor() {
super();
this.x = 2;
super.x = 3; // super.x 赋值为 3,这时等同于对 this.x 赋值为3
console.log(super.x); // undefined,当读取 super.x 的时候,读的是 A.prototype.x,所以返回 undefined
console.log(this.x); // 3
}
}
let b = new B();
// 如果 super 作为对象,用在静态方法之中,这时 super 将指向父类,而不是父类的原型对象
class Parent {
static myMethod(msg) {
console.log('static', msg);
}
myMethod(msg) {
console.log('instance', msg);
}
}
class Child extends Parent {
static myMethod(msg) {
super.myMethod(msg);
}
myMethod(msg) {
super.myMethod(msg);
}
}
Child.myMethod(1); // static 1,super 在静态方法之中指向父类
var child = new Child();
child.myMethod(2); // instance 2,super 在普通方法之中指向父类的原型对象
// 使用 super 的时候,必须显式指定是作为函数、还是作为对象使用,否则会报错
class A {}
class B extends A {
constructor() {
super();
console.log(super); // 报错,无法看出是作为函数使用还是作为对象使用
}
}
// 如果能清晰地表明 super 的数据类型,就不会报错(super.valueOf() 表明 super 是一个对象,因此就不会报错)
class A {}
class B extends A {
constructor() {
super();
console.log(super.valueOf() instanceof B); // true,由于 super 使得 this 指向 B,所以 super.valueOf() 返回的是一个 B 的实例
}
}
let b = new B();
// 由于对象总是继承其他对象的,所以可以在任意一个对象中,使用 super 关键字
var obj = {
toString() {
return "MyObject: " + super.toString();
}
};
obj.toString(); // MyObject: [object Object]
3、类的 prototype 属性 & __proto__
属性
大多数浏览器的 ES5 实现之中,每一个对象都有 __proto__
属性,指向对应的构造函数的 prototype 属性。Class 作为构造函数的语法糖,同时有
prototype 属性和 __proto__
属性,因此同时存在两条继承链。
class A {
}
class B extends A {
}
// 子类的 __proto__ 属性,表示构造函数的继承,总是指向父类
B.__proto__ === A // true
// 子类 prototype 属性的 __proto__ 属性,表示方法的继承,总是指向父类的 prototype 属性
B.prototype.__proto__ === A.prototype // true
// 类的继承是按照下面的模式实现的
class A {
}
class B {
}
Object.setPrototypeOf(B.prototype, A.prototype); // B 的实例继承 A 的实例
Object.setPrototypeOf(B, A); // B 继承 A 的静态属性
const b = new B();
Object.setPrototypeOf = function (obj, proto) { // Object.setPrototypeOf 方法的模拟实现
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 属性)是父类的原型对象(prototype 属性)的实例。
Object.create(A.prototype);
B.prototype.__proto__ = A.prototype; // 等同于
// extends 关键字后面可以跟多种类型的值
class B extends A { // 只要 A 是一个有 prototype 属性的函数,就能被 B 继承。由于函数都有 prototype 属性(除了 Function.prototype 函数),因此 A 可以是任意函数
}
// 特殊情况一:子类继承 Object 类(子类其实就是构造函数 Object 的复制,子类的实例就是 Object 的实例)
class A extends Object {
}
A.__proto__ === Object // true
A.prototype.__proto__ === Object.prototype // true
// 特殊情况二:不存在任何继承
class A {
}
A.__proto__ === Function.prototype // true,A 作为一个基类(即不存在任何继承),就是一个普通函数,所以直接继承 Function.prototype
A.prototype.__proto__ === Object.prototype // true,A 调用后返回一个空对象(即 Object 实例),所以 A.prototype.__proto__ 指向构造函数(Object)的 prototype 属性
// 特殊情况三:子类继承 null
class A extends null {
}
A.__proto__ === Function.prototype // true,A 也是一个普通函数,所以直接继承 Function.prototype
A.prototype.__proto__ === undefined // true,A 调用后返回的对象不继承任何方法,所以它的 prototype.__proto__ 指向 undefined
class C extends null { // 实质上等同于
constructor() { return Object.create(null); }
}
// 子类实例的 __proto__ 属性的 __proto__ 属性,指向父类实例的 __proto__ 属性。也就是说,子类的原型的原型,是父类的原型
var p1 = new Point(2, 3);
var p2 = new ColorPoint(2, 3, 'red');
p2.__proto__ === p1.__proto__ // false
p2.__proto__.__proto__ === p1.__proto__ // true
// 因此,通过子类实例的 __proto__.__proto__ 属性,可以修改父类实例的行为
p2.__proto__.__proto__.printName = function () {
console.log('Ha');
};
p1.printName() // "Ha"
4、原生构造函数的继承
原生构造函数是指语言内置的构造函数,通常用来生成数据结构。ECMAScript 的原生构造函数大致:Boolean()、Number()、String()、Array()、Date()、
Function()、RegExp()、Error()、Object()。以前这些原生构造函数是无法继承的,比如,不能自己定义一个 Array 的子类。
// 定义了一个继承 Array 的 MyArray 类
function MyArray() {
Array.apply(this, arguments);
}
MyArray.prototype = Object.create(Array.prototype, {
constructor: {
value: MyArray,
writable: true,
configurable: true,
enumerable: true
}
});
// 但是这个类的行为与 Array 完全不一致
var colors = new MyArray();
colors[0] = "red";
colors.length // 0
colors.length = 0;
colors[0] // "red"
// 子类无法获得原生构造函数的内部属性,通过 Array.apply() 或者分配给原型对象都不行。原生构造函数会忽略 apply 方法传入的 this,也就是说,
// 原生构造函数的 this 无法绑定,导致拿不到内部属性。ES5 是先新建子类的实例对象 this,再将父类的属性添加到子类上,由于父类的内部属性无法
// 获取,导致无法继承原生的构造函数。比如,Array 构造函数有一个内部属性 [[DefineOwnProperty]],用来定义新属性时,更新 length 属性,这
// 个内部属性无法在子类获取,导致子类的 length 属性行为不正常。
// 让一个普通对象继承 Error 对象,但是 Error.call() 完全忽略传入的第一个参数,而是返回一个新对象,e 本身没有任何变化。这证明了 Error.call(e) 这种写法,无法继承原生构造函数
var e = {};
Object.getOwnPropertyNames(Error.call(e)) // [ 'stack' ]
Object.getOwnPropertyNames(e) // []
// ES6 允许继承原生构造函数定义子类,比如:继承 Array
class MyArray extends Array {
constructor(...args) {
super(...args);
}
}
var arr = new MyArray();
arr[0] = 12;
arr.length // 1
arr.length = 0;
arr[0] // undefined
// ES6 是先新建父类的实例对象 this,然后再用子类的构造函数修饰 this,使得父类的所有行为都可以继承。
// 这意味着,ES6 可以自定义原生数据结构(比如 Array、String 等)的子类,这是 ES5 无法做到的。
// 可以在原生数据结构的基础上,定义自己的数据结构。下面就是定义了一个带版本功能的数组。
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]
// 自定义 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 // true
myerror.name // "MyError"
myerror.stack
// Error
// at MyError.ExtendableError
// ...
// 继承 Object 的子类,有一个行为差异(ES6 改变了 Object 构造函数的行为,一旦发现 Object 方法不是通过 new Object() 这种形式调用,ES6 规定 Object 构造函数会忽略参数)
class NewObj extends Object{
constructor(){
super(...arguments); // NewObj 继承了 Object,但是无法通过 super 方法向父类 Object 传参
}
}
var o = new NewObj({attr: true});
o.attr === true // false
5、Mixin 模式的实现
Mixin 指的是多个对象合成一个新的对象,新对象具有各个组成成员的接口。它的最简单实现如下。
// c 对象是 a 对象和 b 对象的合成,具有两者的接口
const a = {
a: 'a'
};
const b = {
b: 'b'
};
const c = {...a, ...b}; // {a: 'a', b: 'b'}
// 将多个类的接口 "混入"(mix in)另一个类
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) {
// ...
}