# 手写Vue.extend方法
# 概述
用法:使用基础Vue构造器创建一个“子类”,其参数是一个包含“组件选项”的对象。data选项是特例,在Vue.extend()中,它必须是函数。
```
let Custom = Vue.extend({
tempplate:"
{{title}}
"
data() {
return {
title: "vue extend"
}
}
})
new Custom().$mount('test')
```
全局API和实例不一样,是在Vue原型上挂在方法,也就是Vue.prototype上挂载方法
```
Vue.extend = function(extendOptions) {...}
```
作用:Vue.extend的作用是创建一个子类,然后继承Vue身上的一些功能
## 实现
extend实现源码,initExtend会在new Vue时调用
```
function initExtend (Vue) {
Vue.cid = 0;
var cid = 1;
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);
}
var Sub = function VueComponent (options) {
this._init(options);
};
Sub.prototype = Object.create(Super.prototype);
Sub.prototype.constructor = Sub;
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 c