Reflect.defineProperty()

Reflect.defineProperty() 静态方法与 Object.defineProperty() 类似,但返回 Boolean

¥The Reflect.defineProperty() static method is like Object.defineProperty() but returns a Boolean.

Try it

语法

¥Syntax

js
Reflect.defineProperty(target, propertyKey, attributes)

参数

¥Parameters

target

要定义属性的目标对象。

propertyKey

要定义或修改的属性的名称。

attributes

正在定义或修改的属性的属性。

返回值

¥Return value

一个布尔值,指示属性是否已成功定义。

¥A boolean indicating whether or not the property was successfully defined.

例外情况

¥Exceptions

TypeError

如果 targetattributes 不是对象,则抛出该异常。

描述

¥Description

Reflect.defineProperty() 提供了在对象上定义自己的属性的反射语义。在非常低的级别,定义属性返回一个布尔值(如 代理处理程序 的情况)。Object.defineProperty() 提供了几乎相同的语义,但如果状态为 false(操作不成功),它会抛出 TypeError,而 Reflect.defineProperty() 则直接返回状态。

¥Reflect.defineProperty() provides the reflective semantic of defining an own property on an object. At the very low level, defining a property returns a boolean (as is the case with the proxy handler). Object.defineProperty() provides nearly the same semantic, but it throws a TypeError if the status is false (the operation was unsuccessful), while Reflect.defineProperty() directly returns the status.

许多内置操作还会在对象上定义自己的属性。定义属性和 setting 属性之间最显着的区别是 setters 不会被调用。例如,类字段 直接在实例上定义属性,而不调用 setter。

¥Many built-in operations would also define own properties on objects. The most significant difference between defining properties and setting them is that setters aren't invoked. For example, class fields directly define properties on the instance without invoking setters.

js
class B extends class A {
  set a(v) {
    console.log("Setter called");
  }
} {
  a = 1; // Nothing logged
}

Reflect.defineProperty() 调用 target[[DefineOwnProperty]] 对象内部方法

¥Reflect.defineProperty() invokes the [[DefineOwnProperty]] object internal method of target.

示例

¥Examples

使用 Reflect.defineProperty()

¥Using Reflect.defineProperty()

js
const obj = {};
Reflect.defineProperty(obj, "x", { value: 7 }); // true
console.log(obj.x); // 7

检查属性定义是否成功

¥Checking if property definition has been successful

对于 Object.defineProperty(),如果成功则返回一个对象,否则抛出 TypeError,你可以使用 try...catch 块来捕获定义属性时发生的任何错误。

¥With Object.defineProperty(), which returns an object if successful, or throws a TypeError otherwise, you would use a try...catch block to catch any error that occurred while defining a property.

因为 Reflect.defineProperty() 返回布尔成功状态,所以你可以在此处使用 if...else 块:

¥Because Reflect.defineProperty() returns a Boolean success status, you can just use an if...else block here:

js
if (Reflect.defineProperty(target, property, attributes)) {
  // success
} else {
  // failure
}

规范

Specification
ECMAScript Language Specification
# sec-reflect.defineproperty

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看