vue源碼心得--Vue對象生成方式(混入)

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í)!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容