
2025-01-28 日报 Day80

今日的鸡汤
无论遭遇什么,都别灰心丧气,乐观地面对它、积极地解决它,明天才有更好的故事。
今日学习内容
1、JS 红皮书 P276-278 第九章:代理与反射
今日笔记
1、- has(): has()捕获器会在 in 操作符中被调用。对应的反射 API 方法为 Reflect.has()。
1 | const myTarget = {}; |
- 返回值
has()必须返回布尔值,表示属性是否存在。返回非布尔值会被转型为布尔值。 - 拦截的操作
property in proxy
property in Object.create(proxy)
with(proxy) {(property);}
Reflect.has(proxy, property) - 捕获器处理程序参数
target:目标对象。
property:引用的目标对象上的字符串键属性。 - 捕获器不变式
如果 target.property 存在且不可配置,则处理程序必须返回 true。
如果 target.property 存在且目标对象不可扩展,则处理程序必须返回 true。
- defineProperty(): defineProperty()捕获器会在 Object.defineProperty()中被调用。对应的反射 API 方法为 Reflect.defineProperty()。
1
2
3
4
5
6
7
8
9const myTarget = {};
const proxy = new Proxy(myTarget, {
defineProperty(target, property, descriptor) {
console.log('defineProperty()');
return Reflect.defineProperty(...arguments)
}
});
Object.defineProperty(proxy, 'foo', { value: 'bar' });
// defineProperty()
- 返回值
defineProperty()必须返回布尔值,表示属性是否成功定义。返回非布尔值会被转型为布尔值。 - 拦截的操作
Object.defineProperty(proxy, property, descriptor)
Reflect.defineProperty(proxy, property, descriptor) - 捕获器处理程序参数
target:目标对象。
property:引用的目标对象上的字符串键属性。
descriptor:包含可选的 enumerable、configurable、writable、value、get 和 set
定义的对象。 - 捕获器不变式
如果目标对象不可扩展,则无法定义属性。
如果目标对象有一个可配置的属性,则不能添加同名的不可配置属性。
如果目标对象有一个不可配置的属性,则不能添加同名的可配置属性。
- getOwnPropertyDescriptor(): getOwnPropertyDescriptor()捕获器会在 Object.getOwnPropertyDescriptor()中被调用。对应的反射 API 方法为 Reflect.getOwnPropertyDescriptor()。
1
2
3
4
5
6
7
8
9const myTarget = {};
const proxy = new Proxy(myTarget, {
getOwnPropertyDescriptor(target, property) {
console.log('getOwnPropertyDescriptor()');
return Reflect.getOwnPropertyDescriptor(...arguments)
}
});
Object.getOwnPropertyDescriptor(proxy, 'foo');
// getOwnPropertyDescriptor()
- 返回值
getOwnPropertyDescriptor()必须返回对象,或者在属性不存在时返回 undefined。 - 拦截的操作
Object.getOwnPropertyDescriptor(proxy, property)
Reflect.getOwnPropertyDescriptor(proxy, property) - 捕获器处理程序参数
target:目标对象。
property:引用的目标对象上的字符串键属性。 - 捕获器不变式
如果自有的 target.property 存在且不可配置,则处理程序必须返回一个表示该属性存在的对象。
如果自有的 target.property 存在且可配置,则处理程序必须返回表示该属性可配置的对象。
如果自有的 target.property 存在且 target 不可扩展,则处理程序必须返回一个表示该属性存在的对象。
如果 target.property 不存在且 target 不可扩展,则处理程序必须返回 undefined 表示该属性不存在。
如果 target.property 不存在,则处理程序不能返回表示该属性可配置的对象
- deleteProperty(): deleteProperty()捕获器会在 delete 操作符中被调用。对应的反射 API 方法为 Reflect.deleteProperty()。
1
2
3
4
5
6
7
8
9const myTarget = {};
const proxy = new Proxy(myTarget, {
deleteProperty(target, property) {
console.log('deleteProperty()');
return Reflect.deleteProperty(...arguments)
}
});
delete proxy.foo
// deleteProperty()
- 返回值
deleteProperty()必须返回布尔值,表示删除属性是否成功。返回非布尔值会被转型为布尔值。 - 拦截的操作
delete proxy.property
delete proxy[property]
Reflect.deleteProperty(proxy, property) - 捕获器处理程序参数
target:目标对象。
property:引用的目标对象上的字符串键属性。 - 捕获器不变式
如果自有的 target.property 存在且不可配置,则处理程序不能删除这个属性。