前言
在阅读了很多博文后,发现大部分博文都是先代理后反射,这样来说对于一下我来说不是很友好,所以本篇博文将先记录反射,在来记录下代理将会更友好的阅读。
文章目录
JavaScript
的编程思想是面对对象的思想和
函数式编程的思想,二函数式编程的思想就是将所有的操作变为函数操作,比如说
1 + 2
用函数式编程的思想的写法
function add(a, b) {
return a + b;
}
add(1,2);
Reflect 反射
Reflect
反射也就运用了函数式编程的思想,将以前的 new、delete
等等变成了一系列的方法,封装到了 Reflect
对象中。
defineProperty() 设置对象的属性描述
和 Object.defineProperty() 类似,不了解的可以去看我上一篇博文 Object 属性描述符
deleteProperty() 移除对象的属性
const obj = {
a: 1,
b: 2
}
// 使用前
delete obj.a;
// 使用 Reflect
Reflect.deleteProperty(obj, "a")
// {b: 2}
apply() 调用函数
function fun(a, b) {
return a + b;
}
// 使用前
fun(3,4)
// 使用 Reflect
Reflect.apply(fun, null, [3, 4])
// 7
construct() 创建对象
function Test(a, b) {
this.a = a;
this.b = b;
}
// 使用前
const t = new Test(5,6)
// 使用 Reflect
const t = Reflect.construct(Test, [5, 6])
// Test {a: 5, b: 6}
set() 获取属性
const obj = {
a: 1,
b: 2
}
// 使用前
obj.c = 10;
// 使用 Reflect
Reflect.set(obj, "c", 10)
// obj => {a: 1, b: 2, c: 10}
get() 获取属性
const obj = {
a: 1,
b: 2
}
Reflect.get(obj, "a") // 1
getOwnPropertyDescriptor() 返回属性描述符
const obj = {
a: 1,
b: 2
}
Reflect.getOwnPropertyDescriptor(obj, 'a')
// {value: 1, writable: true, enumerable: true, configurable: true}
setPrototypeOf() 设置指定对象的原型
const obj1 = {
a: 1,
b: 2
}
const obj2 = {
a: 3,
b: 4
}
Reflect.setPrototypeOf(obj1, obj2)
// obj1.__proto__ => {a: 3, b: 4}
getPrototypeOf() 返回指定对象的原型
const obj = {
a: 1,
b: 2
}
Reflect.getPrototypeOf(obj)
// obj.__proto__
has() 判断对象是否拥有某个属性
const obj = {
a: 1,
b: 2
}
// 使用前
console.log('a' in obj)
// 使用 Reflect
console.log(Reflect.has(obj, "a"));
// true
isExtensible() 判断一个对象是否可扩展
const obj = {
a: 1,
b: 2
}
// 使用前
Object.isExtensible(obj)
// 使用 Reflect
Reflect.isExtensible(obj)
// true
ownKeys() 以数组的形式返回对象的键
const obj = {
a: 1,
b: 2
}
Reflect.ownKeys(obj)
// ["a", "b"]
preventExtensions() 阻止添加新属性
const obj = {
a: 1,
b: 2
}
Reflect.preventExtensions(obj)
obj.c = 3;
console.log(obj)
// {a: 1, b: 2}
以上就是 Reflect
反射对象里封装的函数方法了,有了 Reflect
反射对象的了解接下来就要来说 Proxy
代理。
Proxy 代理
Proxy
代理提供了修改底层实现的方式,返回一个代理对象。
new Proxy(target,handler)
参数 | 描述 |
---|---|
target | 代理对象 |
handler | 普通对象 |
通过结合 Proxy
代理,可以修改 Reflect
反射底层的代码。
const obj = {
a: 1,
b: 2
}
const proxy = new Proxy(obj, {
set(target, protertyKey, value) {
console.log(`设置了${protertyKey}属性,值为${value}`);
Reflect.set(target, protertyKey, value);
},
get(target, protertyKey) {
console.log(`访问了${protertyKey}属性`);
return Reflect.get(target, protertyKey)
}
})
proxy.a // 访问了a属性
proxy.a = 10 // 设置了a属性,值为10