本系列文章详细深刻Vue.js的源代码,以此来讲明JavaScript的基本概念,尝试将这些概念分解到JavaScript初学者能够理解的水平。有关本系列的一些后续的计划和轨迹的更多信息,请参阅此文章。有关本系列的文章更新进度的信息,请关注个人Tweeter。本系列的文章目录,请查看该连接。html
Vue实例是深刻了解Vue源代码的一个基本点。正如Vue官方文档所说那样,“每一个Vue应用程序都是经过使用Vue函数建立一个新的Vue实例来开始的。”vue
在Vue的源码中,一个新的Vue实例是使用Vue对象的构造函数建立的。ide
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对象构造函数接收一个参数:optionsui
function Vue (options) { [. . . .] }
Vue对象构造函数使用if语句测试当前环境不为生产环境this
[....] 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对象构造函数的实例。prototype
[....] 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做为构造函数来调用。code
[....] if (process.env.NODE_ENV !== ‘production’ && !(this instanceof Vue) ) { warn(‘Vue is a constructor and should be called with the `new` keyword’); } [....]
咱们将会在另外一篇文章来介绍warn函数的实现细节。若是你认真细看,会注意到使用单引号和勾号传递给warn函数。htm
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