prototype 继承
万物皆对象;对象皆有 prototype(原型),prototype 也有 prototype (原型链);在执行某个方法时,如果在 对象中没有找该方法就会 查找原型链 (在prototype上继续查找)
通过 Vue 简单叙述一下
<div class="container" v-cloak>
<button>{{btnText}}</button>
</div>
通过 prototype 继承
// 通过原型链向 Vue 添加 test 函数
Vue.prototype.test = function(name, fn = () => {}){
fn.call(this, name) // 改变了 this 指向
}
var vm = new Vue({
el: '.container',
data: {
btnText: '按钮'
},
mounted() {
// 在 Vue 中本身没有 test 方法
this.test('name', function(res){
// 因为在 test 中改变了 this 的指向,所以该处的 this 依旧是 Vue 实例 按钮会被改变
// 如果 test 中没有改变 this 指向问题,那么这个 this 则是 window 对象
this.btnText = '按钮被改变了'
})
}
})
类继承
HTML 代码不变
ES6 class 继承
class Test extends Vue {
/*
* 注意 Test 的定义也是class关键字实现的,而extends则表示原型链对象来自Vue。
* 子类的构造函数可能会与父类不太相同,例如,Test需要name和tag两个参数,
* 并且需要通过super(name)来调用父类的构造函数,否则父类的name属性无法正常初始化。
*/
constructor(name, tag){
super(name)
this.tag = tag
}
test(name, fn){
fn.call(this, name)
}
}
var vm = new Test({
el: '.container',
data: {
btnText: '按钮'
},
mounted() {
this.test('name', function(res) {
// this 指向的是 Test
console.log(this)
this.btnText = '按钮被改变了'
})
}
})
Test 继承了 Vue 中属性 方法, 用别人的框架,new 自己的构造函数,ennnn… 感觉应该会被揍的不轻吧