zoukankan      html  css  js  c++  java
  • ES6 | 关于class类 继承总结

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

    题图:by Frank from Instagram

    1、class类的继承

    Class 可以通过extends关键字实现继承,这比 ES5 的通过修改原型链实现继承,要清晰和方便很多。

    1 class Point {
    2 }
    3 
    4 class ColorPoint extends Point {
    5 }

    上面代码定义了一个ColorPoint类,该类通过extends关键字,继承了Point类的所有属性和方法。但是由于没有部署任何代码,所以这两个类完全一样,等于复制了一个Point类。下面,我们在ColorPoint内部加上代码。

     1 class ColorPoint extends Point {
     2   constructor(x, y, color) {
     3     super(x, y); // 调用父类的constructor(x, y)
     4     this.color = color;
     5   }
     6 
     7   toString() {
     8     return this.color + ' ' + super.toString(); // 调用父类的toString()
     9   }
    10 }

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

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

    1 class Point { /* ... */ }
    2 
    3 class ColorPoint extends Point {
    4   constructor() {
    5   }
    6 }
    7 
    8 let cp = new ColorPoint(); // ReferenceError

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

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

    ES6 的继承机制完全不同,实质是先创造父类的实例对象this(所以必须先调用super方法),然后再用子类的构造函数修改this

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

    1 class ColorPoint extends Point {
    2 }
    3 
    4 // 等同于
    5 class ColorPoint extends Point {
    6   constructor(...args) {
    7     super(...args);
    8   }
    9 }

    另一个需要注意的地方是,在子类的构造函数中,只有调用super之后,才可以使用this关键字,否则会报错。

    这是因为子类实例的构建,是基于对父类实例加工,只有super方法才能返回父类实例。

     1 class Point {
     2   constructor(x, y) {
     3     this.x = x;
     4     this.y = y;
     5   }
     6 }
     7 
     8 class ColorPoint extends Point {
     9   constructor(x, y, color) {
    10     this.color = color; // ReferenceError
    11     super(x, y);
    12     this.color = color; // 正确
    13   }
    14 }

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

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

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

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

    最后,父类的静态方法,也会被子类继承。

     1 class A {
     2   static hello() {
     3     console.log('hello world');
     4   }
     5 }
     6 
     7 class B extends A {
     8 }
     9 
    10 B.hello()  // hello world

    上面代码中,hello()A类的静态方法,B继承A,也继承了A的静态方法。


    2、Object.getPrototypeOf()

    Object.getPrototypeOf方法可以用来从子类上获取父类。因此,可以使用这个方法判断,一个类是否继承了另一个类。

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

    3、super 关键字

    super这个关键字,既可以当作函数使用,也可以当作对象使用。在这两种情况下,它的用法完全不同。

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

    1 class A {}
    2 
    3 class B extends A {
    4   constructor() {
    5     super();
    6   }
    7 }

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

    注意,super虽然代表了父类A的构造函数,但是返回的是子类B的实例,即super内部的this指的是B,因此super()在这里相当于A.prototype.constructor.call(this)

     1 class A {
     2   constructor() {
     3     console.log(new.target.name);
     4   }
     5 }
     6 class B extends A {
     7   constructor() {
     8     super();
     9   }
    10 }
    11 new A() // A
    12 new B() // B

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

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

    1 class A {}
    2 
    3 class B extends A {
    4   m() {
    5     super(); // 报错
    6   }
    7 }

    上面代码中,super()用在B类的m方法之中,就会造成句法错误。

    第二种情况,super作为对象时,在普通方法中,指向父类的原型对象A.prototype;在静态方法中,指向父类。

    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调用的。

     1 class A {
     2   constructor() {
     3     this.p = 2;
     4   }
     5 }
     6 
     7 class B extends A {
     8   get m() {
     9     return super.p;
    10   }
    11 }
    12 
    13 let b = new B();
    14 b.m // undefined

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

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

     1 class A {}
     2 A.prototype.x = 2;
     3 
     4 class B extends A {
     5   constructor() {
     6     super();
     7     console.log(super.x) // 2
     8   }
     9 }
    10 
    11 let b = new B();

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

    ES6 规定,在子类普通方法中通过super调用父类的方法时,方法内部的this指向当前的子类实例。

     1 class A {
     2   constructor() {
     3     this.x = 1;
     4   }
     5   print() {
     6     console.log(this.x);
     7   }
     8 }
     9 
    10 class B extends A {
    11   constructor() {
    12     super();
    13     this.x = 2;
    14   }
    15   m() {
    16     super.print();
    17   }
    18 }
    19 
    20 let b = new B();
    21 b.m() // 2

    上面代码中,super.print()虽然调用的是A.prototype.print(),但是A.prototype.print()内部的this指向子类B的实例,导致输出的是2,而不是1。也就是说,实际上执行的是super.print.call(this)

    由于this指向子类实例,所以如果通过super对某个属性赋值,这时super就是this,赋值的属性会变成子类实例的属性。

     1 class A {
     2   constructor() {
     3     this.x = 1;
     4   }
     5 }
     6 
     7 class B extends A {
     8   constructor() {
     9     super();
    10     this.x = 2;
    11     super.x = 3;
    12     console.log(super.x); // undefined
    13     console.log(this.x); // 3
    14   }
    15 }
    16 
    17 let b = new B();

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

    如果super作为对象,用在静态方法之中,这时super将指向父类,而不是父类的原型对象。

     1 class Parent {
     2   static myMethod(msg) {
     3     console.log('static', msg);
     4   }
     5 
     6   myMethod(msg) {
     7     console.log('instance', msg);
     8   }
     9 }
    10 
    11 class Child extends Parent {
    12   static myMethod(msg) {
    13     super.myMethod(msg); // super在静态方法之中指向父类
    14   }
    15 
    16   myMethod(msg) {
    17     super.myMethod(msg); // 在普通方法之中指向父类的原型对象
    18   }
    19 }
    20 
    21 Child.myMethod(1); // static 1
    22 
    23 var child = new Child();
    24 child.myMethod(2); // instance 2

    上面代码中,super在静态方法之中指向父类,在普通方法之中指向父类的原型对象。

    另外,在子类的静态方法中通过super调用父类的方法时,方法内部的this指向当前的子类,而不是子类的实例。

     1 class A {
     2   constructor() {
     3     this.x = 1;
     4   }
     5   static print() {
     6     console.log(this.x);
     7   }
     8 }
     9 
    10 class B extends A {
    11   constructor() {
    12     super();
    13     this.x = 2;
    14   }
    15   static m() {
    16     super.print();
    17   }
    18 }
    19 
    20 B.x = 3;
    21 B.m() // 3

    上面代码中,静态方法B.m里面,super.print指向父类的静态方法。这个方法里面的this指向的是B,而不是B的实例。

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

    1 class A {}
    2 
    3 class B extends A {
    4   constructor() {
    5     super();
    6     console.log(super); // 报错
    7   }
    8 }

    上面代码中,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使得this指向B的实例,所以super.valueOf()返回的是一个B的实例。

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

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

    4、 类的 prototype 属性 和 __proto__属性

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

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

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

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

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

    这样的结果是因为,类的继承是按照下面的模式实现的。

     1 class A {
     2 }
     3 
     4 class B {
     5 }
     6 
     7 // B 的实例继承 A 的实例
     8 Object.setPrototypeOf(B.prototype, A.prototype);
     9 
    10 // B 继承 A 的静态属性
    11 Object.setPrototypeOf(B, A);
    12 
    13 const b = new B();

    《对象的扩展》给出过Object.setPrototypeOf方法的实现。

    1 Object.setPrototypeOf = function (obj, proto) {
    2   obj.__proto__ = proto;
    3   return obj;
    4 }

    因此,就得到了上面的结果。

    1 Object.setPrototypeOf(B.prototype, A.prototype);
    2 // 等同于
    3 B.prototype.__proto__ = A.prototype;
    4 
    5 Object.setPrototypeOf(B, A);
    6 // 等同于
    7 B.__proto__ = A;

    这两条继承链,可以这样理解:作为一个对象,子类(B)的原型(__proto__属性)是父类(A);

    作为一个构造函数,子类(B)的原型对象(prototype属性)是父类的原型对象(prototype属性)的实例。

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

    **  extends的继承目标

    extends关键字后面可以跟多种类型的值。

    1 class B extends A {
    2 }

    上面代码的A,只要是一个有prototype属性的函数,就能被B继承。由于函数都有prototype属性(除了Function.prototype函数),因此A可以是任意函数。

    下面,讨论三种特殊情况。

      第一种特殊情况,子类继承Object类:

    1 class A extends Object {
    2 }
    3 
    4 A.__proto__ === Object // true
    5 A.prototype.__proto__ === Object.prototype // true

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

      第二种特殊情况,不存在任何继承:

    1 class A {
    2 }
    3 
    4 A.__proto__ === Function.prototype // true
    5 A.prototype.__proto__ === Object.prototype // true

    这种情况下,A作为一个基类(即不存在任何继承),就是一个普通函数,所以直接继承Function.prototype

    但是,A调用后返回一个空对象(即Object实例),所以A.prototype.__proto__指向构造函数(Object)的prototype属性。

      第三种特殊情况,子类继承null:

    1 class A extends null {
    2 }
    3 
    4 A.__proto__ === Function.prototype // true
    5 A.prototype.__proto__ === undefined // true

    这种情况与第二种情况非常像。A也是一个普通函数,所以直接继承Function.prototype。但是,A调用后返回的对象不继承任何方法,所以它的__proto__指向Function.prototype,即实质上执行了下面的代码。

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

    ** 实例的 __proto__ 属性

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

    1 var p1 = new Point(2, 3);
    2 var p2 = new ColorPoint(2, 3, 'red');
    3 
    4 p2.__proto__ === p1.__proto__ // false
    5 p2.__proto__.__proto__ === p1.__proto__ // true

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

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

    1 p2.__proto__.__proto__.printName = function () {
    2   console.log('Ha');
    3 };
    4 
    5 p1.printName() // "Ha"

    上面代码在ColorPoint的实例p2上向Point类添加方法,结果影响到了Point的实例p1


    5、原生构造函数的继承

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

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

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

     1 function MyArray() {
     2   Array.apply(this, arguments);
     3 }
     4 
     5 MyArray.prototype = Object.create(Array.prototype, {
     6   constructor: {
     7     value: MyArray,
     8     writable: true,
     9     configurable: true,
    10     enumerable: true
    11   }
    12 });

    上面代码定义了一个继承 Array 的MyArray类。但是,这个类的行为与Array完全不一致。

    1 var colors = new MyArray();
    2 colors[0] = "red";
    3 colors.length  // 0
    4 
    5 colors.length = 0;
    6 colors[0]  // "red"

    之所以会发生这种情况,是因为子类无法获得原生构造函数的内部属性,通过Array.apply()或者分配给原型对象都不行。原生构造函数会忽略apply方法传入的this,也就是说,原生构造函数的this无法绑定,导致拿不到内部属性。

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

    下面的例子中,我们想让一个普通对象继承Error对象。

     1 var e = {};
     2 
     3 Object.getOwnPropertyNames(Error.call(e))
     4 // [ 'stack' ]
     5 
     6 Object.getOwnPropertyNames(e)
     7 // []var e = {};
     8 
     9 Object.getOwnPropertyNames(Error.call(e))
    10 // [ 'stack' ]
    11 
    12 Object.getOwnPropertyNames(e)
    13 // []

    上面代码中,我们想通过Error.call(e)这种写法,让普通对象e具有Error对象的实例属性。但是,Error.call()完全忽略传入的第一个参数,而是返回一个新对象,e本身没有任何变化。这证明了Error.call(e)这种写法,无法继承原生构造函数。

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

     1 class MyArray extends Array {
     2   constructor(...args) {
     3     super(...args);
     4   }
     5 }
     6 
     7 var arr = new MyArray();
     8 arr[0] = 12;
     9 arr.length // 1
    10 
    11 arr.length = 0;
    12 arr[0] // undefined

    上面代码定义了一个MyArray类,继承了Array构造函数,因此就可以从MyArray生成数组的实例。这意味着,ES6 可以自定义原生数据结构(比如ArrayString等)的子类,这是 ES5 无法做到的。

    上面这个例子也说明,extends关键字不仅可以用来继承类,还可以用来继承原生的构造函数。因此可以在原生数据结构的基础上,定义自己的数据结构。下面就是定义了一个带版本功能的数组。

     1 class VersionedArray extends Array {
     2   constructor() {
     3     super();
     4     this.history = [[]];
     5   }
     6   commit() {
     7     this.history.push(this.slice());
     8   }
     9   revert() {
    10     this.splice(0, this.length, ...this.history[this.history.length - 1]);
    11   }
    12 }
    13 
    14 var x = new VersionedArray();
    15 
    16 x.push(1);
    17 x.push(2);
    18 x // [1, 2]
    19 x.history // [[]]
    20 
    21 x.commit();
    22 x.history // [[], [1, 2]]
    23 
    24 x.push(3);
    25 x // [1, 2, 3]
    26 x.history // [[], [1, 2]]
    27 
    28 x.revert();
    29 x // [1, 2]
    View Code

    上面代码中,VersionedArray会通过commit方法,将自己的当前状态生成一个版本快照,存入history属性。revert方法用来将数组重置为最新一次保存的版本。除此之外,VersionedArray依然是一个普通数组,所有原生的数组方法都可以在它上面调用。

    下面是一个自定义Error子类的例子,可以用来定制报错时的行为。

     1 class ExtendableError extends Error {
     2   constructor(message) {
     3     super();
     4     this.message = message;
     5     this.stack = (new Error()).stack;
     6     this.name = this.constructor.name;
     7   }
     8 }
     9 
    10 class MyError extends ExtendableError {
    11   constructor(m) {
    12     super(m);
    13   }
    14 }
    15 
    16 var myerror = new MyError('ll');
    17 myerror.message // "ll"
    18 myerror instanceof Error // true
    19 myerror.name // "MyError"
    20 myerror.stack
    21 // Error
    22 //     at MyError.ExtendableError
    23 //     ...
    View Code

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

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

    上面代码中,NewObj继承了Object,但是无法通过super方法向父类Object传参。这是因为 ES6 改变了Object构造函数的行为,一旦发现Object方法不是通过new Object()这种形式调用,ES6 规定Object构造函数会忽略参数。


    6、 Mixin 模式的实现

    Mixin 指的是多个对象合成一个新的对象,新对象具有各个组成成员的接口。它的最简单实现如下。

    1 const a = {
    2   a: 'a'
    3 };
    4 const b = {
    5   b: 'b'
    6 };
    7 const c = {...a, ...b}; // {a: 'a', b: 'b'}

    上面代码中,c对象是a对象和b对象的合成,具有两者的接口。

    下面是一个更完备的实现,将多个类的接口“混入”(mix in)另一个类。

     1 function mix(...mixins) {
     2   class Mix {}
     3 
     4   for (let mixin of mixins) {
     5     copyProperties(Mix, mixin); // 拷贝实例属性
     6     copyProperties(Mix.prototype, mixin.prototype); // 拷贝原型属性
     7   }
     8 
     9   return Mix;
    10 }
    11 
    12 function copyProperties(target, source) {
    13   for (let key of Reflect.ownKeys(source)) {
    14     if ( key !== "constructor"
    15       && key !== "prototype"
    16       && key !== "name"
    17     ) {
    18       let desc = Object.getOwnPropertyDescriptor(source, key);
    19       Object.defineProperty(target, key, desc);
    20     }
    21   }
    22 }

    上面代码的mix函数,可以将多个对象合成为一个类。使用的时候,只要继承这个类即可。

    class DistributedEdit extends mix(Loggable, Serializable) {
      // ...
    }
  • 相关阅读:
    About Face 摘录
    断言的使用
    C#中值传递和引用传递
    C++技巧之断言Assert
    About Face 一 目标导向设计
    About Face 二 设计行为与形态
    C++中引用传递与指针传递区别
    一个新的时代SoLoMo
    离散数学笔记算法部分
    汪教授的离散数学20110308 谓词与量词2
  • 原文地址:https://www.cnblogs.com/wuhaoquan/p/8820706.html
Copyright © 2011-2022 走看看