在Vue源码中,为什么在Vue上挂载了两个相同的方法却都能执行?

entry-runtime-with-compiler.js内

const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && query(el)
  /* istanbul ignore if */
  if (el === document.body || el === document.documentElement) {
    process.env.NODE_ENV !== 'production' && warn(
      `Do not mount Vue to <html> or <body> - mount to normal elements instead.`
    )
    return this
  }
//太长了贴一部分

/runtime/index.js

Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && inBrowser ? query(el) : undefined
  return mountComponent(this, el, hydrating)
}

然后我自己新建几个js试了下为什么不行呢
test.js

function va(){}
export {va}

test1.js

import {va} from './test.js'
va.prototype.hei = function(){
    alert(1)
    console.log(1)
}

test2.js

import {va} from './test.js'
const ob = va.prototype.hei
va.prototype.hei = function(){
    alert(2)
    console.log(2)
}

test3.js

import {va} from './test.js'
var a = new va();
a.hei()

最后只alert2,打印了2
ps:我为了保持相似所以建了好几个..但是为什么不行呢

阅读 3k
3 个回答

源码中const mount = Vue.prototype.$mount
结尾又重新调用 所以执行了两次

你最后一次修改的va.prototype.hei是啥你调用到的就是啥啊,跟你引入的顺序有关系。

新手上路,请多包涵
    var fn1 = function(){console.log('fn1')}
    var fn2 = fn1
    fn1 = function(){
        console.log('fn1 update');
        fn2.call(this);
    }
    fn1() 
    // --> fn1 update
    // --> fn1
推荐问题