JavaScript Object.getOwnPropertyDescriptor()

Object.getOwnPropertyDescriptor() 方法返回对象特定属性的属性描述符。

示例

let obj = {num: 10}

// get the property description // of the num property of obj let numValue = Object.getOwnPropertyDescriptor(obj, "num");
console.log(numValue); // Output: { value: 10, writable: true, enumerable: true, configurable: true }

getOwnPropertyDescriptor() 语法

getOwnPropertyDescriptor() 方法的语法是

Object.getOwnPropertyDescriptor(obj, prop)

这里,getOwnPropertyDescriptor() 是一个静态方法。因此,我们需要使用类名 Object 来访问该方法。


getOwnPropertyDescriptor() 参数

getOwnPropertyDescriptor() 方法接受

  • obj - 要从中查找属性的对象。
  • prop - 要检索其描述的属性的名称或 Symbol

getOwnPropertyDescriptor() 返回值

getOwnPropertyDescriptor() 方法返回

  • 对象指定属性的属性描述符。
  • 如果属性不存在于对象中,则返回 undefined

示例 1: JavaScript Object.getOwnPropertyDescriptor()

let obj = {
  x:  711,
  get number() {
    return this.x;
  },
};

// get property description of x in obj let xDescriptors = Object.getOwnPropertyDescriptor(obj, "x");
console.log(xDescriptors);
// get property description of number() method let value = Object.getOwnPropertyDescriptor(obj, "number");
console.log(value);

输出

{ value: 711, writable: true, enumerable: true, configurable: true }
{
  get: [Function: get number],
  set: undefined,
  enumerable: true,
  configurable: true
}

在此程序中,我们创建了一个具有以下属性的对象 obj

  • x - 值为 711 的属性
  • number() - 一个返回 x 值的 get 方法

然后,我们使用 getOwnPropertyDescriptor() 方法来查找 xnumber() 的属性描述符。

// find property description of x
let xDescriptors = Object.getOwnPropertyDescriptor(obj, "x");

// find property description of number() method
let value = Object.getOwnPropertyDescriptor(obj, "number");

注意传递给 getOwnPropertyDescriptor() 方法的参数。对象名 obj 是没有引号的。

然而,属性名 xnumber 是用双引号括起来的,即 "x""number"


示例 2: getOwnPropertyDescriptor() 与 defineProperty() 结合使用

let obj={}

// define a property of obj using
// the defineProperty() method
Object.defineProperty(obj, "id", {
  value: 123,
  writable: false,
  enumerable: false,
});

// find property description of created property 'id' console.log(Object.getOwnPropertyDescriptor(obj, "id"));

输出

{ value: 123, writable: false, enumerable: false, configurable: false }

在上面的示例中,我们初始化了一个空对象 obj。然后,我们使用 defineProperty() 方法在其上定义了一个单独的属性 id

最后,我们使用 getOwnPropertyDescriptor() 打印了 id 属性的所有属性描述。

结果输出显示,getOwnPropertyDescriptor() 返回的属性描述符与我们使用 defineProperty() 定义的相同。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战