handler.defineProperty()
handler.defineProperty()
方法是对 [[DefineOwnProperty]]
对象内部方法 的陷阱,被 Object.defineProperty()
等操作使用。
¥The handler.defineProperty()
method is a trap for the [[DefineOwnProperty]]
object internal method, which is used by operations such as Object.defineProperty()
.
Try it
语法
参数
¥Parameters
以下参数传递给 defineProperty()
方法。this
绑定到处理程序。
¥The following parameters are passed to the defineProperty()
method.
this
is bound to the handler.
target
-
目标对象。
property
-
要检索其描述的属性的名称或
Symbol
。 descriptor
-
正在定义或修改的属性的描述符。
返回值
描述
拦截
¥Interceptions
该陷阱可以拦截以下操作:
¥This trap can intercept these operations:
或调用 [[DefineOwnProperty]]
内部方法 的任何其他操作。
¥Or any other operation that invokes the [[DefineOwnProperty]]
internal method.
不变量
¥Invariants
如果违反以下不变量,则陷阱在调用时会抛出 TypeError
。
¥If the following invariants are violated, the trap throws a TypeError
when invoked.
- 如果目标对象不可扩展,则无法添加属性。
- 如果属性不作为目标对象的不可配置自有属性存在,则不能将其添加为不可配置属性或将其修改为不可配置属性。
- 如果目标对象存在相应的可配置属性,则属性可能不是不可配置的。
- 如果一个属性有对应的目标对象属性,那么
Object.defineProperty(target, prop, descriptor)
将不会抛出异常。 - 在严格模式下,
defineProperty()
处理程序的false
返回值将引发TypeError
异常。
示例
捕获 defineProperty
¥Trapping of defineProperty
以下代码捕获 Object.defineProperty()
。
¥The following code traps Object.defineProperty()
.
const p = new Proxy(
{},
{
defineProperty(target, prop, descriptor) {
console.log(`called: ${prop}`);
return true;
},
},
);
const desc = { configurable: true, enumerable: true, value: 10 };
Object.defineProperty(p, "a", desc); // "called: a"
当调用 Object.defineProperty()
或 Reflect.defineProperty()
时,传递给 defineProperty()
陷阱的 descriptor
有一个限制 - 只有以下属性可用(非标准属性将被忽略):
¥When calling Object.defineProperty()
or
Reflect.defineProperty()
, the descriptor
passed to
defineProperty()
trap has one restriction—only following properties are
usable (non-standard properties will be ignored):
enumerable
configurable
writable
value
get
set
const p = new Proxy(
{},
{
defineProperty(target, prop, descriptor) {
console.log(descriptor);
return Reflect.defineProperty(target, prop, descriptor);
},
},
);
Object.defineProperty(p, "name", {
value: "proxy",
type: "custom",
}); // { value: 'proxy' }
规范
Specification |
---|
ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc |
浏览器兼容性
BCD tables only load in the browser