Object.getOwnPropertyDescriptor用于获取对象自有属性的描述符,返回含value/get/set等特性的对象;仅对自有属性有效,继承属性返回undefined。

Object.getOwnPropertyDescriptor 是 JavaScript 中用于获取对象**自有属性**(不包括原型链上的属性)的描述符信息的方法。它返回一个描述该属性特性的对象,比如是否可写、是否可枚举、是否可配置,以及属性值或访问器函数等。
基本用法:获取单个属性的描述符
语法很简单:
Object.getOwnPropertyDescriptor(obj, prop)
其中 obj 是目标对象,prop 是要查询的属性名(字符串)。
例如:
const obj = { a: 1 };
const desc = Object.getOwnPropertyDescriptor(obj, 'a');
console.log(desc);
// 输出:{ value: 1, writable: true, enumerable: true, configurable: true }
查看不同属性类型时的返回差异
根据属性是数据属性还是访问器属性,返回的对象结构略有不同:
- 数据属性(普通赋值):包含 value、writable、enumerable、configurable
- 访问器属性(用 get/set 定义):包含 get、set(可能为 undefined)、enumerable、configurable,但没有 value 和 writable
示例:
const obj = {
_x: 10,
get x() { return this._x; },
set x(v) { this._x = v; }
};
console.log(Object.getOwnPropertyDescriptor(obj, 'x'));
// 输出类似:
// { get: [Function: get x], set: [Function: set x], enumerable: true, configurable: true }
注意:只能查自有属性,不能查继承来的
如果属性在原型上,Object.getOwnPropertyDescriptor 会返回 undefined:
const parent = { inherited: 'yes' };
const child = Object.create(parent);
child.own = 'no';
console.log(Object.getOwnPropertyDescriptor(child, 'own')); // ✅ 正常返回
console.log(Object.getOwnPropertyDescriptor(child, 'inherited')); // ❌ undefined
如需检查原型链上的属性,需配合 Object.getPrototypeOf 手动遍历。
结合 Object.defineProperty 使用更清晰
你常会先用 getOwnPropertyDescriptor 查看当前状态,再用 defineProperty 修改它。比如冻结某个属性的可写性:
const obj = { msg: 'hello' };
let desc = Object.getOwnPropertyDescriptor(obj, 'msg');
desc.writable = false;
Object.defineProperty(obj, 'msg', desc);
obj.msg = 'world'; // 严格模式下报错,非严格模式静默失败
不复杂但容易忽略:它只对单个属性有效,查多个属性要用 Object.getOwnPropertyDescriptors(ES2017+)。

















