JavaScript Object.getOwnPropertyDescriptor()
定义和用法
Object.getOwnPropertyDescriptor() 方法返回对象属性的描述符。
Object.getOwnPropertyDescriptor() 方法不会改变原始对象。
相关方法:
Object.defineProperty() 添加或修改属性。
Object.defineProperties() 添加或修改多个属性。
Object.getOwnPropertyNames() 返回对象的所有属性名。
Object.getOwnPropertyDescriptor() 返回属性的描述符。
Object.getOwnPropertyDescriptors() 返回对象所有属性的描述符。
实例
// 创建一个对象
const person = {
firstName: "Bill",
lastName: "Gates",
age: 50,
eyeColor: "blue"
};
// 获取属性描述符
let descriptor = Object.getOwnPropertyDescriptor(person, "firstName");
语法
Object.getOwnPropertyDescriptor(object, property)
参数
| 参数 | 描述 |
|---|---|
| object | 必需。目标对象。 |
| property | 必需。要获取描述符的属性名。 |
返回值
| 类型 | 描述 |
|---|---|
| Object | 属性的描述符对象。 |
浏览器支持
Object.getOwnPropertyDescriptor() 是 ECMAScript5 (ES5) 的特性。
自 2013 年 7 月起,所有现代浏览器均完全支持 ES5(JavaScript 2009):
| Chrome | Edge | Firefox | Safari | Opera |
|---|---|---|---|---|
| Chrome 23 | IE/Edge 11 | Firefox 21 | Safari 6 | Opera 15 |
| 2012 年 9 月 | 2012 年 9 月 | 2013 年 4 月 | 2012 年 7 月 | 2013 年 7 月 |