本篇文章接上一篇Proxy,记录Reflect的学习
文章目录
一、关于Reflect和Proxy?
Proxy 与 Reflect 是 ES6 为了操作对象引入的 API 。
Proxy 可以对目标对象的读取、函数调用等操作进行拦截,然后进行操作处理。它不直接操作对象,而是像代理模式,通过对象的代理对象进行操作,在进行这些操作时,可以添加一些需要的额外操作。
Reflect 可以用于获取目标对象的行为,它与 Object 类似,但是更易读,为操作对象提供了一种更优雅的方式。它的方法与 Proxy 是对应的。
提示:以下是本篇文章正文内容,下面案例可供参考
二、常用场景
1.将Object属于语言内部的方法放到Reflect上
代码如下(示例):
let obj = {}
let newVal = ''
Reflect.defineProperty(obj, 'name', {
get() {
console.log('get')
return newVal
},
set(val) {
console.log(val)
newVal = val
}
})
obj.name = '张三'
console.log(obj.name)
2.修改某些Object方法的返回结果,让其变得合理
代码如下(示例):
try {
Object.defineProperty()
} catch (e) {
console.log(e.message)
}
if (Reflect.defineProperty()) {
} else {
}
3.让Object操作变成函数行为
代码如下(示例):
console.log('assign' in Object) // true
console.log(Reflect.has(Object, 'assign')) // true
4.Reflect对象的方法与Proxy对象的方法一一对应
代码如下(示例):
/**
* 设置_password属性不可访问
* 对于该对象,设置值、获取值、循环遍历、删除属性进行拦截
*/
let userinfo = {
name: '张三',
age: 19,
_password: '******'
}
userinfo = new Proxy(userinfo, {
get(target, prop) {
if (prop.startsWith('_')) {
throw new Error('不可访问')
} else {
// return target[prop]
Reflect.get(target, prop)
}
},
set(target, prop, value) {
if (prop.startsWith('_')) {
throw new Error('不可访问')
} else {
// target[prop] = value
Reflect.set(target, prop, value)
return true
}
},
deleteProperty(target, prop) {
if (prop.startsWith('_')) {
throw new Error('不可访问')
} else {
// delete target[prop]
Reflect.deleteProperty(target, prop)
return true
}
},
ownKeys(target) {
// return Object.keys(target).filter(key => !key.startsWith('_'))
return Reflect.ownKeys(target)
}
})
try {
console.log(userinfo._password)
} catch (e) {
console.log(e.message)
}
try {
userinfo._password = '123456'
} catch (e) {
console.log(e.message)
}
try {
delete userinfo._password
} catch (e) {
console.log(e.message)
}
for (const key in userinfo) {
console.log(key)
}
/**
* 输出
* name
* age
*/
// apply 拦截函数的调用
let sum = function(...args) {
let sum = 0;
args.forEach(value => sum += value)
return sum
}
sum = new Proxy(sum, {
apply(target, context, args) {
console.log('上下文:' + context)
return Reflect.apply(target, target, [...args]) * 2
// return target(...args) * 2
}
})
let obj = {
name: '张三',
age: 19
}
console.log(sum(1, 2, 3))
console.log(sum.call(obj, 1, 2, 3))
console.log(sum.apply(null, [1, 2, 3]))
console.log(sum.call(null, 1, 2, 3))
总结
学习是来自慕课网谢成老师的课程,有需要的同学强推去看一下