object.getownpropertydescriptor用于获取对象自有属性的完整描述符,返回含value/writable或get/set等元信息的对象,若属性不存在或非自有则返回undefined。

Object.getOwnPropertyDescriptor 用于获取对象**自有属性**(非继承)的完整描述符,包括 value、writable、enumerable、configurable 等关键元信息。它不适用于访问器属性(get/set)以外的继承属性或数组索引(除非显式定义为自有属性)。
基本用法:传入对象和属性名
语法很简单:
Object.getOwnPropertyDescriptor(obj, prop)
返回一个描述符对象,如果属性不存在或不是自有属性,则返回 undefined。
例如:
const obj = { name: 'Alice' };
Object.defineProperty(obj, 'age', {
value: 30,
writable: false,
enumerable: true,
configurable: false
});
console.log(Object.getOwnPropertyDescriptor(obj, 'name'));
// { value: 'Alice', writable: true, enumerable: true, configurable: true }
console.log(Object.getOwnPropertyDescriptor(obj, 'age'));
// { value: 30, writable: false, enumerable: true, configurable: false }
console.log(Object.getOwnPropertyDescriptor(obj, 'toString')); // undefined(继承自原型)
区分数据描述符和访问器描述符
描述符有两种类型,返回结果结构不同:
-
数据描述符:含
value和writable(如上面的name和age) -
访问器描述符:含
get和/或set(不含value/writable)
例如定义一个 getter:
const obj = {
_score: 85
};
Object.defineProperty(obj, 'score', {
get() { return this._score; },
set(val) { this._score = Math.max(0, Math.min(100, val)); },
enumerable: true,
configurable: true
});
console.log(Object.getOwnPropertyDescriptor(obj, 'score'));
// { get: ƒ, set: ƒ, enumerable: true, configurable: true }
注意:只查自有属性,不查原型链
即使属性在原型上可枚举,getOwnPropertyDescriptor 也不会返回它:
const parent = { shared: 'yes' };
const child = Object.create(parent);
child.own = 'mine';
console.log(Object.getOwnPropertyDescriptor(child, 'own')); // ✅ 有返回
console.log(Object.getOwnPropertyDescriptor(child, 'shared')); // ❌ undefined
console.log(Object.getOwnPropertyDescriptor(parent, 'shared')); // ✅ 有返回
如需检查原型链上的属性,需手动遍历 Object.getPrototypeOf() 或使用 Object.prototype.propertyIsEnumerable 配合 in 操作符辅助判断。
实用场景:调试属性行为或封装校验逻辑
当你遇到以下情况时,这个 API 很有用:
- 不确定某个属性是否可写(比如被设为
writable: false后赋值静默失败) - 想确认属性是否出现在
for...in或Object.keys()中(看enumerable) - 封装工具函数,自动保护关键属性(检查
configurable === false后禁止再修改) - 做深冻结前验证哪些属性还能被
Object.freeze影响
小技巧:配合 Object.getOwnPropertyDescriptors 可一次性获取所有自有属性描述符,适合批量操作。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











