Vue.extend
用于继承扩展Vue
本身的构造函数,Vue.extend
在initExtend
里面进行定义,initExtend在initGlobalAPI 里面被调用。Vue.extend函数定义如下:
/**
* Each instance constructor, including Vue, has a unique
* cid. This enables us to create wrapped "child
* constructors" for prototypal inheritance and cache them.
*/
Vue.cid = 0;
var cid = 1;
/**
* Class inheritance
*/
Vue.extend = function (extendOptions) {
extendOptions = extendOptions || {};
var Super = this;
var SuperId = Super.cid;
var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {});
if (cachedCtors[SuperId]) {
return cachedCtors[SuperId]
}
var name = extendOptions.name || Super.options.name;
if (name) {
validateComponentName(name);
}
//VueComponent 构造函数
var Sub = function VueComponent (options) {
this._init(options);
};
//继承Vue,寄生式组合继承实现方式,可以参考Javascript 高级程序设计第四版 8.3.6节
Sub.prototype = Object.create(Super.prototype);//通过Object.create以Super.prototype即Vue的prototype,创建一个对象即为当前VueComponent的 prototype
Sub.prototype.constructor = Sub;//指向当前VueComponent 构造函数
Sub.cid = cid++;
Sub.options = mergeOptions(
Super.options,
extendOptions
);
//保存指向父构造函数
Sub['super'] = Super;
// For props and computed properties, we define the proxy getters on
// the Vue instances at extension time, on the extended prototype. This
// avoids Object.defineProperty calls for each instance created.
if (Sub.options.props) {
initProps$1(Sub);
}
if (Sub.options.computed) {
initComputed$1(Sub);
}
// allow further extension/mixin/plugin usage
Sub.extend = Super.extend;
Sub.mixin = Super.mixin;
Sub.use = Super.use;
// create asset registers, so extended classes
// can have their private assets too.
ASSET_TYPES.forEach(function (type) {
Sub[type] = Super[type];
});
// enable recursive self-lookup
if (name) {
Sub.options.components[name] = Sub;
}
// keep a reference to the super options at extension time.
// later at instantiation we can check if Super's options have
// been updated.
Sub.superOptions = Super.options;
Sub.extendOptions = extendOptions;
Sub.sealedOptions = extend({}, Sub.options);
// cache constructor
cachedCtors[SuperId] = Sub;
return Sub
};
Vue.extend 通过寄生式组合继承 对Vue进行继承和扩展,返回一个继承了Vue的VueComponent 构造函数。寄生式组合继承实现方式如下:
function inheritPrototype(subType, superType) {
let prototype = object(superType.prototype); // 创建对象
prototype.constructor = subType; // 增强对象
subType.prototype = prototype; // 赋值对象
}
Vue.extend
和Vue.component
都是返回的一个继承了Vue
的VueComponent
构造函数,区别主要是:
Vue.extend
只是返回了一个继承了Vue
的VueComponent
构造函数,但是Vue.component
除了返回了构造函数外还将这个组件注册到了Vue
的内部,成了一个全局的组件,后续可以通过组件名直接通过标签进行使用。