part1.源碼部分
//位置src\core\instance\index.js
import { initMixin } from './init'
import { stateMixin } from './state'
import { renderMixin } from './render'
import { eventsMixin } from './events'
import { lifecycleMixin } from './lifecycle'
import { warn } from '../util/index'
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)
}
initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)
export default Vue
這里的Vue對象實際上就是通過Vue構(gòu)造函數(shù)實現(xiàn),即:
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)
}
為何 Vue 不用 ES6 的 Class 去實現(xiàn)呢?我們往后看這里有很多 xxxMixin 的函數(shù)調(diào)用,并把 Vue 當(dāng)參數(shù)傳入,它們的功能都是給 Vue 的 prototype 上擴展一些方法(這里具體的細節(jié)會在之后的文章介紹,這里不展開),Vue 按功能把這些擴展分散到多個模塊中去實現(xiàn),而不是在一個模塊里實現(xiàn)所有,這種方式是用 Class 難以實現(xiàn)的。這么做的好處是非常方便代碼的維護和管理。
part2.模塊實現(xiàn)
function Warlock(){
this._init({
name:'warlock',
year:'21',
})
}
function initObj(obj){
obj.prototype._init=function(option){
this.name=option.name;
this.year=option.year;
}
}
initObj(Warlock)
let obj=new Warlock();
warlock對象的init的方法就通過下面的initObj“混入”,
現(xiàn)在打開F12,復(fù)制上段代碼并復(fù)制控制臺之,運行,看看obj的結(jié)果

obj
這就是vue的通過混入的模塊管理方式,非常值得我們學(xué)習(xí)!