JS逐日一题:new Vue()中发生了什么?

20190214问

new Vue()中发生了什么?

先从语法上剖析,new关键字在js言语中代表实例化一个对象, 而Vue实际上是一个类, 我们简朴看一下源码

源码地点
https://github.com/vuejs/vue/…

// 从源码能够看到vue类中异常清洁,只是实行了一个_init私有函数, 而且只能经由过程new关键字初始化
function Vue (options) {
  if (process.env.NODE_ENV !== 'production' &&
    !(this instanceof Vue)
  ) {
    warn('Vue is a constructor and should be called with the `new` keyword')
  }
  this._init(options)
}

接着我们追踪至_init函数

源码地点
https://github.com/vuejs/vue/…

export function initMixin (Vue: Class<Component>) {
  Vue.prototype._init = function (options?: Object) {
    const vm: Component = this
    // a uid
    vm._uid = uid++

    let startTag, endTag
    /* istanbul ignore if */
    if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
      startTag = `vue-perf-start:${vm._uid}`
      endTag = `vue-perf-end:${vm._uid}`
      mark(startTag)
    }

    // a flag to avoid this being observed
    vm._isVue = true
    // merge options
    if (options && options._isComponent) {
      // optimize internal component instantiation
      // since dynamic options merging is pretty slow, and none of the
      // internal component options needs special treatment.
      initInternalComponent(vm, options)
    } else {
      vm.$options = mergeOptions(
        resolveConstructorOptions(vm.constructor),
        options || {},
        vm
      )
    }
    /* istanbul ignore else */
    if (process.env.NODE_ENV !== 'production') {
      initProxy(vm)
    } else {
      vm._renderProxy = vm
    }
    // expose real self
    vm._self = vm
    initLifecycle(vm)
    initEvents(vm)
    initRender(vm)
    callHook(vm, 'beforeCreate')
    initInjections(vm) // resolve injections before data/props
    initState(vm)
    initProvide(vm) // resolve provide after data/props
    callHook(vm, 'created')

    /* istanbul ignore if */
    if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
      vm._name = formatComponentName(vm, false)
      mark(endTag)
      measure(`vue ${vm._name} init`, startTag, endTag)
    }

    if (vm.$options.el) {
      vm.$mount(vm.$options.el)
    }
  }
}

从上面的代码我们瞥见_init很清淅的干了几件事, 兼并相干设置, 初始化生命周期,初始化事宜中间,初始化衬着,初始化 data、props、computed、watcher 等

题外话

Vue初始化逻辑异常清淅,把差别的功用拆成一些零丁的函数实行,这类头脑值得自创和进修

关于JS逐日一题

JS逐日一题能够看成是一个语音答题社区
天天应用碎片时候采纳60秒内的语音情势来完成当天的考题
群主在越日0点推送当天的参考答案

  • 注 毫不仅限于完成当天使命,更多是查漏补缺,进修群内别的同砚优异的答题思绪

点击到场答题

    原文作者:febobo
    原文地址: https://segmentfault.com/a/1190000018160928
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞