Object.getOwnPropertyDescriptor() 方法返回指定对象上一个自有属性对应的属性描述符。
(自有属性指的是直接赋予该对象的属性,不需要从原型链上进行查找的属性)
const object1 = {
property1: 42
};
const descriptor1 = Object.getOwnPropertyDescriptor(object1, 'property1');
console.log(descriptor1.configurable);
// expected output: true
console.log(descriptor1.value);
// expected output: 42
描述
该方法允许对一个属性的描述进行检索。在 Javascript 中, 属性 由一个字符串类型的“名字”(name)和一个“属性描述符”(property descriptor)对象构成。更多关于属性描述符类型以及他们属性的信息可以查看:Object.defineProperty.
一个属性描述符是一个记录,由下面属性当中的某些组成的:
value
该属性的值(仅针对数据属性描述符有效)
writable
当且仅当属性的值可以被改变时为true。(仅针对数据属性描述有效)
get
获取该属性的访问器函数(getter)。如果没有访问器, 该值为undefined。(仅针对包含访问器或设置器的属性描述有效)
set
获取该属性的设置器函数(setter)。 如果没有设置器, 该值为undefined。(仅针对包含访问器或设置器的属性描述有效)
configurable
当且仅当指定对象的属性描述可以被改变或者属性可被删除时,为true。
enumerable
当且仅当指定对象的属性可以被枚举出时,为 true。
var o, d;
o = { get foo() { return 17; } };
d = Object.getOwnPropertyDescriptor(o, "foo");
// d {
// configurable: true,
// enumerable: true,
// get: /*the getter function*/,
// set: undefined
// }
o = { bar: 42 };
d = Object.getOwnPropertyDescriptor(o, "bar");
// d {
// configurable: true,
// enumerable: true,
// value: 42,
// writable: true
// }
o = {};
Object.defineProperty(o, "baz", {
value: 8675309,
writable: false,
enumerable: false
});
d = Object.getOwnPropertyDescriptor(o, "baz");
// d {
// value: 8675309,
// writable: false,
// enumerable: false,
// configurable: false
// }
Object.getOwnPropertyDescriptors()
code:
const object1 = {
property1 : 42 ,
property2 : 2
};
const descriptor1 = Object.getOwnPropertyDescriptor(object1, 'property1');
console.log(Object.entries(descriptor1))
var dess = Object.getOwnPropertyDescriptors(object1 )
console.log(Object.entries(dess))
print:
[
[ 'value', 42 ],
[ 'writable', true ],
[ 'enumerable', true ],
[ 'configurable', true ]
]
[
[
'property1',
{ value: 42, writable: true, enumerable: true, configurable: true }
],
[
'property2',
{ value: 2, writable: true, enumerable: true, configurable: true }
]
从打印中我们可以看到他拥有所有的
3. Create() + Object.getOwnPropertyDescriptors()实现对象浅拷贝
回顾Create+assign实现混合继承的代码:
function MyClass() {
SuperClass.call(this);
OtherSuperClass.call(this);
}
// 继承一个类
MyClass.prototype = Object.create(SuperClass.prototype);
// 混合其它
Object.assign(MyClass.prototype, OtherSuperClass.prototype);
// 重新指定constructor
MyClass.prototype.constructor = MyClass;
MyClass.prototype.myMethod = function() {
// do a thing
};
问题:Object.assign(MyClass.prototype, OtherSuperClass.prototype)
Object.assign() 方法只能拷贝源对象的可枚举的自身属性,同时拷贝时无法拷贝属性的特性们,而且访问器属性会被转换成数据属性,也无法拷贝源对象的原型,该
因此当我们要的是拷贝对象的时候就应该使用:
Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj)
);
4. 优雅创建子类的方式
function superclass() {}
superclass.prototype = {
// 在这里定义方法和属性
};
function subclass() {}
subclass.prototype = Object.create(superclass.prototype, Object.getOwnPropertyDescriptors({
// 在这里定义方法和属性
}));