Reflect常结合proxy使用,在这里所有的案例就直接结合proxy直接使用。如果不是很懂proxy可以支持戳连接查看相关资料
get
let obj = {
name: "前端伪大叔",
age: 19
}
let newObj = new Proxy(obj, {
get(target, property) {
if (property in target)
return Reflect.get(target, property)
else
throw new Error(`${property}不在${target}上面`)
}
})
console.log(newObj.name); // 前端伪大叔
console.log(newObj.hello); // Uncaught Error: hello不在[object Object]上面
set
let obj = {
name: "前端伪大叔",
age: 19
}
let newObj = new Proxy(obj, {
set(target,property,value){
if(target[property] === value){
return target[property]
}else{
return Reflect.set(target,property,value)
}
}
})
console.log(newObj.name);
newObj.name = '前端伪大叔'
console.log(newObj.name);
newObj.name = '前端'
console.log(newObj.name);
has
和in运算符同理
let obj = {
name: "前端伪大叔",
age: 19
}
let newObj = new Proxy(obj, {
has(target,property){
return Reflect.has(target,property)
}
})
console.log('name' in newObj); // true
console.log('sex' in newObj) // false
deleteProperty
删除指定的元素和属性。返回
boolean
值
let newObj = new Proxy(obj, {
deleteProperty(target,property){
return Reflect.deleteProperty(target,property)
}
})
delete newObj.name
console.log(newOb
isExtensible
判断对象是否可以扩容,如果传入的不是对象会直接报错
let obj = {}
let arr = []
let fun = ()=>{}
let str = 'a'
let num = 123;
let bool = false
let any;
console.log(Reflect.isExtensible(obj));
console.log(Reflect.isExtensible(arr));
console.log(Reflect.isExtensible(fun));
// console.log(Reflect.isExtensible(str)); 报错
// console.log(Reflect.isExtensible(num)); 报错
// console.log(Reflect.isExtensible(bool)); 报错
// console.log(Reflect.isExtensible(any)); 报错
preventExtensions
和上面的相反,preventExtensions
是把一个可以扩容的对象转为 不可扩容
,返回boolean值。
let obj = {}
console.log(Reflect.isExtensible(obj)); // true
Reflect.preventExtensions(obj) // 返回boolean值
console.log(Reflect.isExtensible(obj)); // false
ownKeys
获取所有对象的key值。以数组形式返回所有的key值。
let obj = {
name: "前端伪大叔",
fun() {
return 'hello world'
},
list: [1, 2, 3, 4]
}
console.log(Reflect.ownKeys(obj)['name']); // ["name", "fun", "list"]