美文网首页
Class 的继承

Class 的继承

作者: 了凡和纤风 | 来源:发表于2019-10-21 13:47 被阅读0次

    一、简介

    Class 可以通过 extends 关键字实现继承,这比 ES5 通过修改原型链实现继承更加清晰和方便。使用继承,子类必须在 constructor 方法中调用 super 方法,否则新建实例时会保错,这是因为子类没有自己的 this 对象,而是继承父类的 this 对象,然后对其进行加工。如果不调用 super 方法,子类就得不到 this 对象

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

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

    如果子类没有定义 constructor 方法,那么这个方法会默认添加即,无论有没有显示定义,任何一个子类都有 constructor 方法

    class ColorPoint extends Point {}
    
    // 等同于
    class ColorPoint extends Point {
      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()
        this.color = color // 正确
      }
    }
    

    生成子类实例

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

    实例对象 cp 同时是 ColorPoint 和 Point 两个类的实例,这与 ES5 的行为完全一致

    二、Object.getPrototyof()

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

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

    可以使用这个方法判断一个类是否继承了另一个类

    三、super 关键字

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

    1. 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() // A
    new B() // B
    

    可以看出,在 super() 执行是,它指向的是子类 B 的构造函数,而不是父类 A 的构造函数。也就是说,super() 内部的this指向的是B

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

    class A {}
    
    class B extends A {
      m() {
        super() // 报错
      }
    }
    
    1. 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 调用的。如果属性定义在父类的原型对象上,super 就可以取到

    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
    

    A.prototype.print() 会绑定之类 B 的this,导致输出的是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
      }
    }
    

    super.x 被赋值为 3,等同于 对 this.x 赋值为 3。当读取super.x时,相当于读取的是 A.prototype.x,所以返回 undefined

    如果 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
    
    var child = new Child()
    child.myMethod(2) // instance 2
    

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

    使用 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 绑定 B 的this,所以 super.valueOf() 返回的是一个 B 的实例。


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

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

    四、类的 prototype 属性和 __proto__ 属性

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

    • 子类的 __proto__ 属性表示构造函数的继承,总是指向父类
    • 子类 prototype 属性的 __proto__ 属性表示方法的继承,总是指向父类的 prototype 属性。
    class A {}
    
    class B extends A {}
    
    B.__proto__ === A // true
    B.prototype.__proto__ === A.prototype // true
    

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

    class A {}
    
    class B {}
    
    // B 的实例继承 A 的实例
    Object.setPrototypeOf(B.prototype, A.prototype)
    // B 的实例继承 A 的静态属性
    Object.setPrototypeOf(B, A)
    
    const b = new B()
    

    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
    

    4.1 extends 的继承目标

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

    class B extends A {
    }
    

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

    下面,讨论三种特殊情况

    1. 子类继承 Object 类
    class A extends Object {}
    
    A.__proto__ === Object // true
    A.prototype.__proto__ = Object.prototype // true
    

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

    1. 不存在任何继承
    class A {}
    
    A.__proto__ === Function,prototype // true
    A.prototype.__proto__ === Object.prototype // true
    

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

    1. 子类继承 null
    class A extends null {}
    
    A.__proto__ === Function.prototype // true
    A.prototype.__proto__ === undefined // true
    

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

    即实质上执行了下面的代码

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

    4.2、实例的 proto 属性

    子类实例的 __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__ 属性修改父类实例的行为

    五、原生构造函数的继承

    原生构造函数是指语言内置的构造函数,通常用来生成数据结构。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,
        wirtable: true,
        configurable: true,
        enumerable: true
      }
    })
    

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

    var colors = new MyArray
    color[0] = 'red'
    colors.length // 0
    
    colors.length = 0;
    colors[0] // 'red'
    

    之所以会发生这种情况,是因为子类无法获得原生构造函数的内部属性,通过 Array.apply() 或者 分配给原型对象都不行。原生构造函数会忽略 apply 方法传入的 this,也就是说,原生构造函数的 this 无法绑定,导致拿不到内部属性。比如,Array 构造函数有一个内部属性 [[ DefineOwnProperty ]],用来定义新属性时,更新 length 属性,这个内部属性便无法在子类获取,导致子类的 length 属性行为不正常。

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

    下面是一个继承 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 可以自定义原生数据结构(比如 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.history // [[], [1, 2]]
    
    x.revert()
    x // [1, 2]
    

    VersionedArray 会通过 commit 方法将自己的当前状态生成一个变笨快照并存入 history 属性。revert 方法用来将数组重置为最新一次保存的版本。

    下面是一个自定义 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('11')
    myerror.message // "11"
    myerror instanceof Error // true
    myerror.name // "MyError"
    myerror.stack
    // "Error
    //    at new ExtendableError ......
    

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

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

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

    六、Mixin 模式的的实现

    Mixin 模式指的是将多个类的接口 “混入”(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) {
      // ...
    }
    

    相关文章

      网友评论

          本文标题:Class 的继承

          本文链接:https://www.haomeiwen.com/subject/nndamctx.html