04-谈谈Vue中的类继承——Vue.extend

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
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值