Object.getOwnPropertyDescriptors()
Object.getOwnPropertyDescriptors()
静态方法返回给定对象的所有自己的属性描述符。
¥The Object.getOwnPropertyDescriptors()
static method returns all
own property descriptors of a given object.
Try it
语法
参数
返回值
描述
¥Description
该方法允许检查对象所有自身属性的精确描述。JavaScript 中的属性由字符串值名称或 Symbol
和属性描述符组成。有关属性描述符类型及其属性的更多信息可以在 Object.defineProperty()
中找到。
¥This method permits examination of the precise description of all own properties of an
object. A property in JavaScript consists of either a string-valued name or a
Symbol
and a property descriptor. Further information about property
descriptor types and their attributes can be found in
Object.defineProperty()
.
属性描述符是具有以下一些属性的记录:
¥A property descriptor is a record with some of the following attributes:
value
-
与属性关联的值(仅限数据描述符)。
writable
-
true
当且仅当与属性关联的值可以更改时(仅限数据描述符)。 get
-
充当属性的 getter 的函数,如果没有 getter,则为
undefined
(仅限访问器描述符)。 set
-
充当属性 setter 的函数,如果没有 setter,则为
undefined
(仅限访问器描述符)。 configurable
-
true
当且仅当该属性描述符的类型可以更改并且该属性可以从相应的对象中删除时。 enumerable
-
true
当且仅当该属性在相应对象的属性枚举过程中出现时。
示例
创建浅拷贝
¥Creating a shallow copy
虽然 Object.assign()
方法只会将可枚举的属性和自己的属性从源对象复制到目标对象,但你可以将此方法和 Object.create()
用于两个未知对象之间的 浅拷贝:
¥Whereas the Object.assign()
method will only copy enumerable and own
properties from a source object to a target object, you are able to use this method and
Object.create()
for a shallow copy between two unknown objects:
Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj),
);
创建子类
¥Creating a subclass
创建子类的典型方法是定义子类,将其原型设置为超类的实例,然后在该实例上定义属性。这可能会变得很尴尬,尤其是对于 getter 和 setter 来说。相反,你可以使用以下代码来设置原型:
¥A typical way of creating a subclass is to define the subclass, set its prototype to an instance of the superclass, and then define properties on that instance. This can get awkward especially for getters and setters. Instead, you can use this code to set the prototype:
function superclass() {}
superclass.prototype = {
// Define the superclass constructor, methods, and properties here
};
function subclass() {}
subclass.prototype = Object.create(superclass.prototype, {
// Define the subclass constructor, methods, and properties here
});
规范
Specification |
---|
ECMAScript Language Specification # sec-object.getownpropertydescriptors |
浏览器兼容性
BCD tables only load in the browser