【译】Vue源码学习(一):Vue对象构造函数

本系列文章详细深入Vue.js的源代码,以此来说明JavaScript的基本概念,尝试将这些概念分解到JavaScript初学者可以理解的水平。有关本系列的一些后续的计划和轨迹的更多信息,请参阅此文章。有关本系列的文章更新进度的信息,请关注我的Tweeter。本系列的文章目录,请查看该链接

Vue对象构造函数

Vue实例是深入了解Vue源代码的一个基本点。正如Vue官方文档所说那样,“每个Vue应用程序都是通过使用Vue函数创建一个新的Vue实例来开始的。”

在Vue的源码中,一个新的Vue实例是使用Vue对象的构造函数创建的。

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);
}

一个对象的构造函数是创建其他对象的一个蓝本。对象构造函数按约定通常是以大写字母开头。

function Vue (options) {
[. . . .]
}

通过new关键字来调用一个对象构造函数。例如,你应该会按一下方式调用Vue构造函数:

var vm = new Vue({
  // options
})

调用对象构造函数会返回一个新的对象,并且将this关键字指向为返回的对象。
Vue对象构造函数接收一个参数:options

function Vue (options) {
[. . . .]
}

Vue对象构造函数使用if语句测试当前环境不为生产环境

[....]
  if (process.env.NODE_ENV !== 'production' &&
    !(this instanceof Vue)
  ) {
    warn('Vue is a constructor and should be called with the `new` keyword');
  }
[....]

如果当前环境为生产环境,则&&短路逻辑为false,其余的表达式则不执行。
如果是在开发环境,对象构造函数会检查this是否不是Vue对象构造函数的实例。

[....]
  if (process.env.NODE_ENV !== ‘production’ &&
    !(this instanceof Vue)
  ) {
    warn(‘Vue is a constructor and should be called with the `new` keyword’);
  }
[....]

如果是在开发环境下并且this不是Vue对象构造函数的实例,则该对象构造函数调用warn函数并传入一个字符串作为一个参数,通知开发者使用new关键字将Vue作为构造函数来调用。

[....]
  if (process.env.NODE_ENV !== ‘production’ &&
    !(this instanceof Vue)
  ) {
    warn(‘Vue is a constructor and should be called with the `new` keyword’);
  }
[....]

我们将会在另一篇文章来介绍warn函数的实现细节。如果你认真细看,会注意到使用单引号和勾号传递给warn函数。

warn('Vue is a constructor and should be called with the `new` keyword');

在单引号中间使用勾号明显的好处是具有防止引用过早结束。

最后,Vue构造函数调用方法this._init 并且传入参数options

function Vue (options) {
  [....]
  this._init(options);
}

但等一下,_init方法在this对象中哪里定义的?正如我们所见,这个方法并没有定义在构造函数中。快速查找源码可以发现该._init在一个名为initMixin的单独函数中加到了Vue.prototype中。
我们下次再详细介绍initMixin。如果你喜欢这个系列,并想激励我继续努力,鼓励,跟随,回应或分享你的内心。

下一篇:initMixin函数

(END 2019/05/19)

原文链接

https://medium.com/@oneminutejs/a-deep-dive-in-the-vue-js-source-code-fd9638c05c05

原文地址:https://www.cnblogs.com/GeniusLyzh/p/10916537.html