core/global-api/extend.js

这个类继承是专用的,只用来创建Vue的子类的,也就是各种组件类的创建。因此这里面的代码有很多硬编码的东西。去除跟Vue强相关的内容的话,剩下的就是一个典型的类继承,在别的源码库里也都见过的。

经过extend后,子类上会有父类(Vue)的那些方法:

  • extend
  • use
  • mixin
  • component
  • filter
  • directive
    同时还会有以下四个options:
  • options 子类的选项
  • extendedOptions 创建子类时的选项
  • superOptions 父类的选项
  • sealedOptions 浅拷贝了一份options

Sub.options的计算也是一个复杂的过程可以参考这里

需要说明的是extend方法如果在Vue上调用,则是返回继承Vue的子类。所有Vue的子类也都有extend方法,也能在Sub调用extend,此时返回的就是子类的子类了。我就是想说我们不仅可以继承Vue,也能继承子类。

Vue.extend = function (extendOptions: Object): Function {
    extendOptions = extendOptions || {}
    const Super = this
    const SuperId = Super.cid
    const cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {})
    if (cachedCtors[SuperId]) {
      return cachedCtors[SuperId]
    }

    const name = extendOptions.name || Super.options.name
    if (process.env.NODE_ENV !== 'production' && name) {
      validateComponentName(name)
    }

    // 子组建的构造函数,调用了父类(Vue)的_init方法
    const Sub = function VueComponent (options) {
      this._init(options)
    }
    // 原型链实现继承
    Sub.prototype = Object.create(Super.prototype)
    Sub.prototype.constructor = Sub
    Sub.cid = cid++
    // 把Vue的options继承下来
    Sub.options = mergeOptions(
      Super.options,
      extendOptions
    )
    Sub['super'] = Super

    // For props and computed properties, we define the proxy getters on
    // the Vue instances at extension time, on the extended prototype. This
    // avoids Object.defineProperty calls for each instance created.
    if (Sub.options.props) {
      initProps(Sub)
    }
    if (Sub.options.computed) {
      initComputed(Sub)
    }

    // allow further extension/mixin/plugin usage
    Sub.extend = Super.extend
    Sub.mixin = Super.mixin
    Sub.use = Super.use

    // create asset registers, so extended classes
    // can have their private assets too.
    ASSET_TYPES.forEach(function (type) {
      Sub[type] = Super[type]
    })
    // enable recursive self-lookup
    // 递归
    if (name) {
      Sub.options.components[name] = Sub
    }

    // keep a reference to the super options at extension time.
    // later at instantiation we can check if Super's options have
    // been updated.
    Sub.superOptions = Super.options
    Sub.extendOptions = extendOptions
    Sub.sealedOptions = extend({}, Sub.options)

    // cache constructor
    cachedCtors[SuperId] = Sub
    return Sub
  }
Logo

前往低代码交流专区

更多推荐