JS进阶 | Proxy代理对象
理解的视频——b站——【经典面试题】ES6中的proxy和Reflect
想要实现:
const arr = [1,2,3,4]
console.log(arr[-1]) // 应打印出4 此时打印出undefined
相关知识学习:
代码
let star = {
name: 'zhoujielun',
age: '30',
phoneNumber: 'xxxxxxxxx'
}
// 代理陷阱
let proxy = new Proxy(star, {
get: function(target, key, receiver) {
if(key === 'phoneNumber') {
return '经纪人电话: 13899172797'
}else {
// return target[key]
return Reflect.get(target, key, receiver)
}
}
})
console.log(proxy.name)
console.log(proxy.age)
console.log(proxy.phoneNumber)
解决最上面的问题:
代码:
let arr = [1,2,3,4]
function createArray(arr) {
let handle = {
get: function (target, index, receiver) {
index = Number(index)
if(index < 0) {
index += target.length
}
return Reflect.get(target, index, receiver)
}
}
return new Proxy(arr, handle)
}
arr = createArray(arr)
console.log(arr[-1])
console.log(arr[-2])