vue2.0源碼 - 數組監控方法:
思路:
攔截數組方法,原型鏈指向自己定義的原型,內部實際還是調用的原生方法。。。
下邊switch是判斷數據是否需要定義響應式,可忽略!
let obj= {
test:[1,2,3]
}
let old = Array.prototype
let o = Object.create(old)
const methods = [
'unshift',
'pop',
'sort',
'reverse',
'splice',
'push'
]
methods.forEach(method => {
o[method] = function (...arg) {
let result = old[method].apply(this, arg)
let varible
console.log(`用戶調用了 ${method}`)
switch(method) {
case 'push':
case 'unshift':
varible = arg
break
case 'splice':
varible = arg.slice(2)
}
return result
}
})
obj['test'].__proto__ = o
console.log(obj['test'].push('123'))
補充:
Object.create () 創建一個全新的對象
創建一個全新的對象,它的原型爲:現有對象,也就是傳的參數,此時,新創建的對象的__proto__(指向原型)就是傳的參數。
參數:必傳,null或對象
eg:
let proto = {
info: 'test',
intro: function() { console.log(`my name is ${this.myname}`)}
}
let person = Object.create(proto)
person.myname = 'lxc'
person.intro()