handler.getOwnPropertyDescriptor()
handler.getOwnPropertyDescriptor()
方法是对 [[GetOwnProperty]]
对象内部方法 的陷阱,被 Object.getOwnPropertyDescriptor()
等操作使用。
¥The handler.getOwnPropertyDescriptor()
method is a trap for the [[GetOwnProperty]]
object internal method, which is used by operations such as Object.getOwnPropertyDescriptor()
.
Try it
语法
参数
返回值
描述
拦截
¥Interceptions
该陷阱可以拦截以下操作:
¥This trap can intercept these operations:
或调用 [[GetOwnProperty]]
内部方法 的任何其他操作。
¥Or any other operation that invokes the [[GetOwnProperty]]
internal method.
不变量
¥Invariants
如果违反以下不变量,则陷阱在调用时会抛出 TypeError
。
¥If the following invariants are violated, the trap throws a TypeError
when invoked.
getOwnPropertyDescriptor()
必须返回一个对象或undefined
。- 如果属性作为目标对象的不可配置自有属性存在,则不能将其报告为不存在。
- 如果属性作为目标对象自己的属性存在并且目标对象不可扩展,则不能将其报告为不存在。
- 如果属性不作为目标对象自己的属性存在并且目标对象不可扩展,则不能将其报告为存在。
- 如果某个属性不作为目标对象的自有属性存在,或者作为目标对象的可配置自有属性存在,则该属性不能报告为不可配置。
Object.getOwnPropertyDescriptor(target)
的结果可以使用Object.defineProperty()
应用到目标对象,并且不会抛出异常。
示例
getOwnPropertyDescriptor 的捕获
¥Trapping of getOwnPropertyDescriptor
以下代码捕获 Object.getOwnPropertyDescriptor()
。
¥The following code traps Object.getOwnPropertyDescriptor()
.
const p = new Proxy(
{ a: 20 },
{
getOwnPropertyDescriptor(target, prop) {
console.log(`called: ${prop}`);
return { configurable: true, enumerable: true, value: 10 };
},
},
);
console.log(Object.getOwnPropertyDescriptor(p, "a").value);
// "called: a"
// 10
以下代码违反了不变量。
¥The following code violates an invariant.
const obj = { a: 10 };
Object.preventExtensions(obj);
const p = new Proxy(obj, {
getOwnPropertyDescriptor(target, prop) {
return undefined;
},
});
Object.getOwnPropertyDescriptor(p, "a"); // TypeError is thrown
规范
Specification |
---|
ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p |
浏览器兼容性
BCD tables only load in the browser