一、Object.defineProperty
定義:Object.defineProperty() 方法會直接在一個對象上定義一個新屬性,或者修改一個對象的現(xiàn)有屬性,并返回此對象
為什么能實現(xiàn)響應式
通過defineProperty 兩個屬性,get及set
-
get
屬性的 getter 函數(shù),當訪問該屬性時,會調(diào)用此函數(shù)。執(zhí)行時不傳入任何參數(shù),但是會傳入 this 對象(由于繼承關(guān)系,這里的this并不一定是定義該屬性的對象)。該函數(shù)的返回值會被用作屬性的值 -
set
屬性的 setter 函數(shù),當屬性值被修改時,會調(diào)用此函數(shù)。該方法接受一個參數(shù)(也就是被賦予的新值),會傳入賦值時的 this 對象。默認為 undefined
下面通過代碼展示:
定義一個響應式函數(shù)defineReactive
function update() {
app.innerText = obj.foo
}
function defineReactive(obj, key, val) {
Object.defineProperty(obj, key, {
get() {
console.log(`get ${key}:${val}`);
return val
},
set(newVal) {
if (newVal !== val) {
val = newVal
update()
}
}
})
}
調(diào)用defineReactive,數(shù)據(jù)發(fā)生變化觸發(fā)update方法,實現(xiàn)數(shù)據(jù)響應式
const obj = {}
defineReactive(obj, 'foo', '')
setTimeout(()=>{
obj.foo = new Date().toLocaleTimeString()
},1000)
在對象存在多個key情況下,需要進行遍歷
function observe(obj) {
if (typeof obj !== 'object' || obj == null) {
return
}
Object.keys(obj).forEach(key => {
defineReactive(obj, key, obj[key])
})
}
如果存在嵌套對象的情況,還需要在defineReactive中進行遞歸
function defineReactive(obj, key, val) {
observe(val)
Object.defineProperty(obj, key, {
get() {
console.log(`get ${key}:${val}`);
return val
},
set(newVal) {
if (newVal !== val) {
val = newVal
update()
}
}
})
}
當給key賦值為對象的時候,還需要在set屬性中進行遞歸
set(newVal) {
if (newVal !== val) {
observe(newVal) // 新值是對象的情況
notifyUpdate()
}
}
上述例子能夠?qū)崿F(xiàn)對一個對象的基本響應式,但仍然存在諸多問題
現(xiàn)在對一個對象進行刪除與添加屬性操作,無法劫持到
const obj = {
foo: "foo",
bar: "bar"
}
observe(obj)
delete obj.foo // no ok
obj.jar = 'xxx' // no ok
當我們對一個數(shù)組進行監(jiān)聽的時候,并不那么好使了
const arrData = [1,2,3,4,5];
arrData.forEach((val,index)=>{
defineProperty(arrData,index,val)
})
arrData.push() // no ok
arrData.pop() // no ok
arrDate[0] = 99 // ok
可以看到數(shù)據(jù)的api無法劫持到,從而無法實現(xiàn)數(shù)據(jù)響應式,
所以在Vue2中,增加了set、delete API,并且對數(shù)組api方法進行一個重寫
還有一個問題則是,如果存在深層的嵌套對象關(guān)系,需要深層的進行監(jiān)聽,造成了性能的極大問題
小結(jié)
檢測不到對象屬性的添加和刪除
數(shù)組API方法無法監(jiān)聽到
需要對每個屬性進行遍歷監(jiān)聽,如果嵌套對象,需要深層監(jiān)聽,造成性能問題
二、proxy
Proxy的監(jiān)聽是針對一個對象的,那么對這個對象的所有操作會進入監(jiān)聽操作,這就完全可以代理所有屬性了
在ES6系列中,我們詳細講解過Proxy的使用,就不再述說了
下面通過代碼進行展示:
定義一個響應式方法reactive
function reactive(obj) {
if (typeof obj !== 'object' && obj != null) {
return obj
}
// Proxy相當于在對象外層加攔截
const observed = new Proxy(obj, {
get(target, key, receiver) {
const res = Reflect.get(target, key, receiver)
console.log(`獲取${key}:${res}`)
return res
},
set(target, key, value, receiver) {
const res = Reflect.set(target, key, value, receiver)
console.log(`設置${key}:${value}`)
return res
},
deleteProperty(target, key) {
const res = Reflect.deleteProperty(target, key)
console.log(`刪除${key}:${res}`)
return res
}
})
return observed
}
測試一下簡單數(shù)據(jù)的操作,發(fā)現(xiàn)都能劫持
const state = reactive({
foo: 'foo'
})
// 1.獲取
state.foo // ok
// 2.設置已存在屬性
state.foo = 'fooooooo' // ok
// 3.設置不存在屬性
state.dong = 'dong' // ok
// 4.刪除屬性
delete state.dong // ok
再測試嵌套對象情況,這時候發(fā)現(xiàn)就不那么 OK 了
const state = reactive({
bar: { a: 1 }
})
// 設置嵌套對象屬性
state.bar.a = 10 // no ok
如果要解決,需要在get之上再進行一層代理
function reactive(obj) {
if (typeof obj !== 'object' && obj != null) {
return obj
}
// Proxy相當于在對象外層加攔截
const observed = new Proxy(obj, {
get(target, key, receiver) {
const res = Reflect.get(target, key, receiver)
console.log(`獲取${key}:${res}`)
return isObject(res) ? reactive(res) : res
},
return observed
}
三、總結(jié)
Object.defineProperty只能遍歷對象屬性進行劫持
function observe(obj) {
if (typeof obj !== 'object' || obj == null) {
return
}
Object.keys(obj).forEach(key => {
defineReactive(obj, key, obj[key])
})
}
Proxy直接可以劫持整個對象,并返回一個新對象,我們可以只操作新的對象達到響應式目的
function reactive(obj) {
if (typeof obj !== 'object' && obj != null) {
return obj
}
// Proxy相當于在對象外層加攔截
const observed = new Proxy(obj, {
get(target, key, receiver) {
const res = Reflect.get(target, key, receiver)
console.log(`獲取${key}:${res}`)
return res
},
set(target, key, value, receiver) {
const res = Reflect.set(target, key, value, receiver)
console.log(`設置${key}:${value}`)
return res
},
deleteProperty(target, key) {
const res = Reflect.deleteProperty(target, key)
console.log(`刪除${key}:${res}`)
return res
}
})
return observed
}
Proxy可以直接監(jiān)聽數(shù)組的變化(push、shift、splice)
const obj = [1,2,3]
const proxtObj = reactive(obj)
obj.psuh(4) // ok
Proxy有多達13種攔截方法,不限于apply、ownKeys、deleteProperty、has等等,這是Object.defineProperty不具備的
正因為defineProperty自身的缺陷,導致Vue2在實現(xiàn)響應式過程需要實現(xiàn)其他的方法輔助(如重寫數(shù)組方法、增加額外set、delete方法)
// 數(shù)組重寫
const originalProto = Array.prototype
const arrayProto = Object.create(originalProto)
['push', 'pop', 'shift', 'unshift', 'splice', 'reverse', 'sort'].forEach(method => {
arrayProto[method] = function () {
originalProto[method].apply(this.arguments)
dep.notice()
}
});
// set、delete
Vue.set(obj,'bar','newbar')
Vue.delete(obj),'bar')
Proxy 不兼容IE,也沒有 polyfill, defineProperty 能支持到IE9