什么`args.unshift(this)`在Vue的use.js中做什么?

时间:2017-01-30 14:35:51

标签: vue.js

我正在阅读vuejs源代码,并对这两行代码感到困惑:

const args = toArray(arguments, 1)
args.unshift(this)

在下面的代码片段中,为什么还要这样做?

/* @flow */

import { toArray } from '../util/index'

export function initUse (Vue: GlobalAPI) {
  Vue.use = function (plugin: Function | Object) {
    /* istanbul ignore if */
    if (plugin.installed) {
      return
    }
    // additional parameters
    const args = toArray(arguments, 1)
    args.unshift(this)
    if (typeof plugin.install === 'function') {
      plugin.install.apply(plugin, args)
    } else {
      plugin.apply(null, args)
    }
    plugin.installed = true
    return this
  }
}

1 个答案:

答案 0 :(得分:0)

由于您位于Vue实例内,所涉及的行位于Vue.use上定义的函数中,这很可能会引用当前的Vue实例。

你必须浏览toArray的来源以理解第一行,它可能需要参数并从中返回一个数组,并且可能减去第一个参数(toArray(arguments, 1)中的1)我这个印象,但要确保浏览该功能的来源)。

但是当调用args.unshift(this)到来时,它将Vue实例作为args array的第一个元素,然后用于为plugin函数提供参数

希望有所帮助; - )

的Seb