概念
Proxy 可以理解成蚯窥,在目標(biāo)對(duì)象之前架設(shè)一層“攔截”掸鹅,外界對(duì)該對(duì)象的訪問(wèn),都必須先通過(guò)這層攔截拦赠,因此提供了一種機(jī)制河劝,可以對(duì)外界的訪問(wèn)進(jìn)行過(guò)濾和改寫(xiě)。
語(yǔ)法
let p = new Proxy(target, handler);
set
const obj = { name: '' }
const proxy = new Proxy(obj, {
set: (target, prop, value) => {
target[prop] = value.toString().toUpperCase();
},
})
proxy.name = 'a';
console.log(obj)
console.log(proxy)
get
const obj = {
name: 'a'
}
const proxy = new Proxy(obj, {
get: (target, prop) => {
return target[prop].toString().toUpperCase()
}
})
console.log(proxy.name)
has
const obj = { name: '' }
const proxy = new Proxy(obj, {
has: (target, prop) => {
console.log(`call ${prop} values ${target[prop]}`)
return target[prop] !== undefined;
},
})
console.log('name' in proxy)
deleteProperty
const obj = {
a: 1,
b: 2
}
const proxy = new Proxy(obj, {
deleteProperty: (target, prop) => {
if (prop === 'b') {
return false
}
delete target[prop]
return true
}
})
delete proxy.b
console.log(obj)
delete proxy.a
console.log(obj)
apply
function sum(a, b) {
return a + b;
}
const absSum = new Proxy(sum, {
apply(target, thisArg, args) {
const value = target.apply(thisArg, args);
return value < 0 ? -value : value;
}
});
console.log(absSum(-1, -2));
更多API見(jiàn)https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy#
Proxy 相比于 Object.defineProperty 優(yōu)勢(shì)
監(jiān)聽(tīng)數(shù)組事件
const obj = {}
var list = [1, 2, 3]
Object.defineProperty(obj, 'list', {
get: () => {
return list
},
set: (newVal) => {
console.log(newVal)
list = newVal
}
})
obj.list.push(4)
obj.list = [1, 2, 3, 4, 5]
const list = [1, 2, 3]
var proxyObj = new Proxy(list, {
set: (target, property, value) => {
console.log('set')
console.log(property, value)
return Reflect.set(target, property, value);
}
})
proxyObj.push(4)
Reflect對(duì)象與Proxy對(duì)象一樣矛紫,也是ES6為了操作對(duì)象而提供的新API赎瞎。
詳見(jiàn): https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Reflect
監(jiān)聽(tīng)的是一整個(gè)對(duì)象而非對(duì)象的某個(gè)屬性
let p = new Proxy(target, handler);
vs
Object.defineProperty(obj, prop, descriptor)
支持嵌套代理
let obj = {
info: {
name: 'eason',
blogs: ['webpack', 'babel', 'cache']
}
}
let handler = {
get(target, key) {
console.log('get', key)
// 遞歸創(chuàng)建并返回
if (typeof target[key] === 'object' && target[key] !== null) {
return new Proxy(target[key], handler)
}
return Reflect.get(target, key)
},
set(target, key, value) {
console.log('set', key, value)
return Reflect.set(target, key, value)
}
}
let proxy = new Proxy(obj, handler)
// 以下兩句都能夠進(jìn)入 set
proxy.info.name = 'Zoe'
proxy.info.blogs.push('proxy')
使用場(chǎng)景
實(shí)現(xiàn)觀察者模式
Vue 3.0 使用 Proxy 代替 Object.defineProperty 實(shí)現(xiàn)雙向綁定
數(shù)據(jù)校驗(yàn)
const obj = {
phone: '13888888888'
}
const proxy = new Proxy(obj, {
set: (target, prop, value) => {
if (prop === 'phone' && !/^(\+86)?1[\d]{10}$/.test(value)) {
return false;
}
target[prop] = value;
return true;
}
})
proxy.phone = 'a'
console.log(proxy)
proxy.phone = '13899999999'
console.log(proxy)
添加實(shí)用方法
const list = [
{ name: 'a', phone: '13888888888' },
{ name: 'b', phone: '13899999999' },
];
const proxyList = new Proxy(list, {
get: (target, prop) => {
if (prop in target) {
return target[prop];
}
for (const item of target) {
if (item.name === prop) {
return item;
}
}
return undefined;
}
});
console.log(proxyList[0]);
console.log(proxyList["a"]);
Proxy的坑
this指向問(wèn)題
const target = {
m: function () {
console.log(this === target);
}
};
const proxy = new Proxy(target, {});
target.m() // true
proxy.m() // false
解決
const target = {
m: function () {
console.log(this === target);
}
};
const proxy = new Proxy(target, {
get(target, prop) {
return target[prop].bind(target);
}
});
target.m() // true
proxy.m() // true